本文共 1093 字,大约阅读时间需要 3 分钟。
思路:SAX工厂-->SAX解析器-->SAX阅读器-->注册事件处理-->解析开始。
对应代码:
public class TestSAX {
public static void main(String[] args) throws Exception{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(new MyContentHandler());
reader.parse("book.xml");
}
}
class MyContentHandler extends DefaultHandler {
private String elementName = null;
@Override
public void startDocument() throws SAXException {
System.out.println("文档解析开始>>>>>>>>>>>>>>>>>>>>>>>>");
}
@Override
public void startElement(String arg0, String arg1, String arg2,
Attributes arg3) throws SAXException {
elementName = arg2;
}
@Override
public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
if ("书名".equals(elementName)) {
System.out.println(new String(arg0, arg1, arg2));
}
}
@Override
public void endElement(String arg0, String arg1, String arg2)
throws SAXException {
elementName = null;
}
@Override
public void endDocument() throws SAXException {
System.out.println("文档解析结束>>>>>>>>>>>>>>>>>>>>>>>>");
}
}
转载地址:http://dkyhp.baihongyu.com/