假设我要读取的xml文件是limaoyuan.xml内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person>
<name>李茂源</name>
<age>24</age>
</person>
<person>
<name>哈哈</name>
<age>22</age>
</person>
</persons>
继承DefaultHandler的解析器
package com.xmlservice;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import domain.Person;
public class PersonHandler extends DefaultHandler {
private List<Person> persons=null;
private Person person=null;
private String tag="";
public List<Person> getPersons() {
return persons;
}
@Override
public void startDocument() throws SAXException {
persons=new ArrayList<Person>();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if("person".equals(qName)){
person=new Person();
}
tag=qName;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if(person!=null){
String data=new String(ch,start,length);
if("name".equals(tag)){
person.setName(data);
}else if("age".equals(tag)){
person.setAge(Integer.parseInt(data));
}
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(person!=null&&"person".equals(qName)){
persons.add(person);
person=null;
}
tag=null;
}
}
业务类,使用自写的处理器,对xml解析
package com.xmlservice;
import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import domain.Person;
public class XMLParserService {
public static List<Person> readXml(InputStream inStream)throws Exception{
//sax解析工厂
SAXParserFactory factory=SAXParserFactory.newInstance();
//构造SAX解析器
SAXParser parser=factory.newSAXParser();
PersonHandler handler=new PersonHandler();
parser.parse(inStream, handler); //使用指定的handler对流inStream进行解析
List<Person> persons=handler.getPersons();//返回内容
return persons;
}
}
测试类
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import org.junit.Test;
import com.xmlservice.XMLParserService;
import domain.Person;
public class XMLParserTest {
@Test //使用了JUnit4进行测试
public void testReadXml(){
try{
//文件的位置在该工程的WebRoot/xmlfile/文件下
File file=new File("WebRoot/xmlfile/limaoyuan.xml");
InputStream inStream=new FileInputStream(file);
//注意,我的limaoyuan.xml这个文件是放在工程的src目录下的,当然你也可以读取其它目录的文件
//InputStream inStream=XMLParserTest.class.getClassLoader().getResourceAsStream("limaoyuan.xml");
List<Person> persons=XMLParserService.readXml(inStream);
for(Person person:persons){
System.out.println(person.toString());
}
}catch(Exception e){
e.printStackTrace();
}
}
}