public class SAXTestXml {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
// 获得解析工厂
SAXParserFactory factory = SAXParserFactory.newInstance();
// 从解析工厂获取解析器
SAXParser parser = factory.newSAXParser();
// 编写处理器 加载文档 Document 注册处理器
PHandler handler = new PHandler();
// 解析
parser.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream("com/temp/sax_xml/person.xml"), handler);
List<Person> persons = handler.getPersons();
System.out.println(persons.size());
for (Person person : persons) {
System.out.println(person);
}
}
}
class PHandler extends DefaultHandler {
private List<Person> persons;
private Person person;
private String elementName;
public List<Person> getPersons(){
return this.persons;
}
@Override
public void startDocument() throws SAXException {
persons = new ArrayList<>();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (null!=qName) {
elementName = qName;
if ("person".equals(qName)) {
person=new Person();
if (null!=attributes) {
person.setId(attributes.getValue("id"));
}
}
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String contents = new String(ch, start, length);
if (null!=contents&&!contents.isEmpty()) {
contents = contents.trim();
if ("name".equals(elementName)) {
person.setName(contents);
}else if("age".equals(elementName)) {
if (contents.length()>0) {
person.setAge(Integer.valueOf(contents));
}
}
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if ("person".equals(qName)) {
persons.add(person);
}
elementName = null;
}
@Override
public void endDocument() throws SAXException {
}
}
class Person{
private String name;
private int age;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", id=" + id + "]";
}
}
xml
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="2212312313">
<name>晓明</name>
<age>100</age>
</person>
<person id="8776856786">
<name>晴雪</name>
<age>22</age>
</person>
</persons>
结果
2
Person [name=晓明, age=100, id=2212312313]
Person [name=晴雪, age=22, id=8776856786]
©著作权归作者所有:来自51CTO博客作者huingsn的原创作品,如需转载,请注明出处,否则将追究法律责任
共同学习,写下你的评论
评论加载中...
作者其他优质文章