sax解析个人感觉是非常麻烦的,但是是sun公司的标准,所以还是必须得学习:示例代码有两个功能,一个是列出所有的标签和标签的值,一个是列出你想要的标签的值
xml文件:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><persons>
<person>
<name>wuyihua</name>
<grade>98</grade>
<id>1</id></person>
<person job="student">
<name>zengxiangjian</name>
<grade>100</grade>
<id>3</id></person>
</persons>
解析类:
package com.saxparser.domain;
import javax.sql.rowset.spi.XmlReader;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
public class Demo1 {
/**
* @param args
* @throws Exception
* @throws ParserConfigurationException
*/
public static void main(String[] args) throws ParserConfigurationException,
Exception {
SAXParserFactory fa = SAXParserFactory.newInstance();// 得解析工厂
SAXParser parser = fa.newSAXParser();// 得解析器
XMLReader reader = parser.getXMLReader();// 得到数据
reader.setContentHandler(new ListHandler());// 设置解析器,解析器要自己写;
reader.parse("src/person.xml");// 获取xml文档内容
}
}
class ListHandler extends DefaultHandler {
private String current;// 记录现在的标签
private String needTag;// 记录你想要的标签
private int currentNum;// 记录现在是第几个标签
private String tagValue;
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
System.out.println("<" + qName + ">");// 打印所有的开始标签
current = qName;
for (int i = 0; i < attributes.getLength() && attributes != null; i++) {// for遍历所有的属性
System.out.println(attributes.getValue(i));
}
super.startElement(uri, localName, qName, attributes);
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if ("name".equals(current)) {//这里我想获取第一个name标签的值
needTag = current;
tagValue = new String(ch, start, length);
System.err.println(tagValue);// 用err来标记想要的标签的值
}
System.out.println(new String(ch, start, length));// 打印所有的标签的值
super.characters(ch, start, length);
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
current = null;
System.out.println("</" + qName + ">");// 打印结束标签的名称
super.endElement(uri, localName, qName);
}
}