1.概述
SAX(simple API for XML)是一种XML解析的替代方法。相比于DOM,SAX是一种速度更快,更有效的方法。
2.XML文件
在类路径下新建xml文件
boot.xml
<?xml version="1.0" encoding="UTF-8" ?>
<book id="1">
<name>Java核心技术</name>
<author>Cay S. Horstmann</author>
<isbn lang="CN">1234567</isbn>
<tags>
<tag>Java</tag>
<tag>Network</tag>
</tags>
<pubDate/>
</book>
3.使用SAX解析XML
@Test
public void test() throws Exception {
InputStream input = SAXTest.class.getResourceAsStream("/book.xml");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser saxParser = spf.newSAXParser();
saxParser.parse(input, new MyHandler());
}
class MyHandler extends DefaultHandler {
@Override
public void startDocument() throws SAXException {
// System.out.println("start document");
}
@Override
public void endDocument() throws SAXException {
// System.out.println("end document");
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
StringBuilder builder = new StringBuilder();
builder.append("<");
builder.append(qName);
// 处理属性
for (int i = 0; i < attributes.getLength(); ++i) {
String attrName = attributes.getQName(i);
String attrValue = attributes.getValue(i);
builder.append(String.format(" %s='%s' ", attrName, attrValue));
}
builder.append(">");
System.out.print(builder.toString());
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
System.out.print("</" + qName + ">");
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String str = new String(ch, start, length);
System.out.print(str);
}
@Override
public void error(SAXParseException e) throws SAXException {
System.out.print("error:" + e);
}
}