<?xml version="1.0" encoding="UTF-8" ?>
<sax>
<s>tao</s>
<a>taoge</a>
<x>1234</x>
</sax>
----------------------
package tao.test;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class Handler extends DefaultHandler {
private StringBuilder sb = new StringBuilder();
@Override
public void startDocument() throws SAXException {
System.out.println("---------- start document ------------");
}
@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
sb.append("<").append(name).append(">");
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
sb.append(new String(ch, start, length));
}
@Override
public void endElement(String uri, String localName, String name)
throws SAXException {
sb.append("</").append(name).append(">");
}
@Override
public void endDocument() throws SAXException {
System.out.println(sb);
System.out.println("---------- end document ------------");
}
}
==========================================
//创建一个 saxParser 对象
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
sp.parse(this.class.getResourceAsStream("/sax.xml"), new Handler());