JavaSAX解析XML第一步:自定义一个类继承DefaultHandler
JavaSAX解析XML第二步:重写startDocument
、startElement
、characters
、endElement
、endDocument
方法
JavaSAX解析XML第三步:
- 开始读取文档时创建
ArrayList
用来存储对象
- 开始读取某个元素时根据元素标签名创建相应的对象,并记录当前访问的节点,此时可以获得元素的属性
- 获取元素的文本内容时,根据记录的访问节点,给创建的对象相应的属性赋值
- 结束读取某个元素时,把对象添加到
ArrayList
中,并清空记录的当前节点
- 结束读取文档的时候就可以返回
ArrayList
XML文件
<Users>
<user id="9527">
<name>admin</name>
<age>40</age>
<hobby>manage someone!</hobby>
</user>
<user id="9632">
<name>chenghui</name>
<age>110</age>
<hobby>code something!</hobby>
</user>
</Users>
自定义的SAXParseService
package com.javawu.sax;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
//自定义一个类集成DefaultHandler类
//在该类中实现xml的解析
public class SAXParseService extends DefaultHandler {
private List<User> list = null;
private String currentTag = null;//记录当前访问的节点名
private User user = null;
//开始读取文档
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
list = new ArrayList<>();
}
//开始读某个元素
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if(qName.equals("user")) {
user = new User();
user.setId(attributes.getValue("id"));
}
currentTag = qName;
}
//获取元素的文本内容
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
// TODO Auto-generated method stub
if(currentTag == null) {
return;
}
String content = new String(ch, start, length);
switch (currentTag) {
case "name":
user.setName(content);
break;
case "age":
user.setAge(Integer.parseInt(content));
break;
case "hobby":
user.setHobby(content);
break;
default:
break;
}
}
//结束读某个元素
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// TODO Auto-generated method stub
if(qName.equals("user")) {
list.add(user);
}
currentTag = null;
}
//结束读取文档
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
for (User user : list) {
System.out.println(user);
}
}
}
使用自定的类解析XML
package com.javawu.sax;
import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class Demo1 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//创建SAX解析器工厂类对象
SAXParserFactory saxParseFactory = SAXParserFactory.newInstance();
//创建SAX解析器对象
SAXParser saxParser = saxParseFactory.newSAXParser();
//解析
saxParser.parse(new File("./UserInfo.xml"), new SAXParseService());
}
}