复制代码代码如下:
包com.test;
导入java.io.File;
导入 java.io.FileInputStream;
导入java.util.ArrayList;
导入java.util.List;
导入 javax.xml.parsers.SAXParser;
导入 javax.xml.parsers.SAXParserFactory;
导入 org.xml.sax.Attributes;
导入 org.xml.sax.SAXException;
导入 org.xml.sax.helpers.DefaultHandler;
公共类 SaxXML {
公共静态无效主(字符串[] args){
文件 file = new File("e:/People.xml");
尝试 {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser 解析器 = spf.newSAXParser();
SaxHandler 处理程序 = new SaxHandler("People");
parser.parse(new FileInputStream(file), handler);
List<People> peopleList = handler.getPeoples();
为(人民人民:人民名单){
System.out.println(people.getId()+"/t"+people.getName()+"/t"+people.getEnglishName()+"/t"+people.getAge());
}
} catch (异常 e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
类 SaxHandler 扩展 DefaultHandler {
私有列表 <People> peoples = null;
私人人士;
私有字符串 currentTag = null;
私有字符串当前值 = null;
私有字符串节点名称 = null;
公共列表 <People> getPeoples() {
回归人民;
}
公共 SaxHandler(字符串节点名称) {
this.nodeName = 节点名称;
}
@覆盖
公共无效startDocument()抛出SAXException {
// TODO 当读到一个开始标签的时候,会触发这个方法
super.startDocument();
peoples = new ArrayList<People>();
}
@覆盖
公共无效endDocument()抛出SAXException {
// TODO 自动生成的方法存根
super.endDocument();
}
@覆盖
公共无效startElement(字符串uri,字符串本地名称,字符串名称,
属性属性)抛出 SAXException {
// TODO 当遇到文档的引用的时候,调用这个方法
super.startElement(uri, localName, 名称, 属性);
if (name.equals(nodeName)) {
人=新人();
}
if (属性!= null && 人们!= null) {
for (int i = 0; i < attribute.getLength(); i++) {
if(attributes.getQName(i).equals("id")){
people.setId(attributes.getValue(i));
}
否则 if(attributes.getQName(i).equals("en")){
people.setEnglishName(attributes.getValue(i));
}
}
}
当前标签=名称;
}
@覆盖
公共无效字符(char [] ch,int开始,int长度)
抛出 SAXException {
// TODO 这个方法用于处理在 XML 文件中读取到的内容
super.characters(ch, 开始, 长度);
if (currentTag!= null && people!= null) {
currentValue = new String(ch, 开始, 长度);
if (currentValue != null && !currentValue.trim().equals("") && !currentValue.trim().equals("/n")) {
if(currentTag.equals("名称")){
people.setName(currentValue);
}
否则 if(currentTag.equals("年龄")){
people.setAge(currentValue);
}
}
}
当前标签=空;
当前值=空;
}
@覆盖
公共无效endElement(字符串uri,字符串本地名称,字符串名称)
抛出 SAXException {
// TODO 在遇到结束标签的时候,调用这个方法
super.endElement(uri, localName, 名称);
if (name.equals(nodeName)) {
peoples.add(people);
}
}
}