<?xml version="1.0" encoding="UTF-8" ?>
<persons>
<person>
<name>张三</name>
<age>18</age>
</person>
<person>
<name>李四</name>
<age>20</age>
</person>
</persons>
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<Person> list = handler.getList();
System.out.println(list);
}
}
class PersonHandler extends DefaultHandler {
private Person person;
private ArrayList<Person> list;
private String tag;
public ArrayList<Person> 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));
}
}
}
网友评论