xml解析



    
        张三
        18
    

    
        李四
        20
    

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;

import static java.lang.Thread.activeCount;
import static java.lang.Thread.currentThread;

public class XMLTest01 {
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        PersonHandler handler = new PersonHandler();
        saxParser.parse(currentThread().getContextClassLoader().getResourceAsStream("p.xml"), handler);
        ArrayList list = handler.getList();
        System.out.println(list);

    }


}

class PersonHandler extends DefaultHandler {

    private Person person;
    private ArrayList list;
    private String tag;

    public ArrayList getList() {
        return list;
    }

    @Override
    public void startDocument() throws SAXException {
        list = new ArrayList<>();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        System.out.println();
        System.out.println("start-->" + qName);
        tag = qName;
        if (qName.equals("person")) {
            person = new Person();
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        System.out.println();
        System.out.println("end-->" + qName);
        if (qName.equals("person")) {
            list.add(person);
        }
        tag = "";
        tag = null;
    }

    @Override
    public void endDocument() throws SAXException {
//        System.out.println(list);
        System.out.println("stop-----");
        System.out.println("============");
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String content = new String(ch, start, length);
        System.out.println("content--->" + content);
//        if (tag.equals("name")) {
//            person.setName(content);
//        } else if (tag.equals("age")) {
//            person.setAge(Integer.parseInt(content));
//        }
        if (Objects.equals(tag, "name")) {
            person.setName(content);
        } else if (Objects.equals(tag, "age")) {
            person.setAge(Integer.parseInt(content));
        }
    }
}

你可能感兴趣的:(xml解析)