可以使用SAXParser的parse方法進行解析,也可以使用XmlReader的parse方法進行解析,但是最好是使用XmlReader,因為XmlReader是接口。
基本的初始化方法如下:
File f=new File("d:"+File.separator+"e.xml");
InputSource ip=new InputSource(new FileInputStream(f));
try {
SAXParser s=SAXParserFactory.newInstance().newSAXParser();
XMLReader xmlReader=s.getXMLReader();
xmlReader.setContentHandler(new MyHandler());
xmlReader.parse(ip);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
其中MyHandler類繼承了DefaultHandler,可以overwrite其中的方法,使其滿足需求。
例子:
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
if (logger.isInfoEnabled()) {
logger
.info("startElement(String, String, String, Attributes) - uri="
+ uri
+ ", localName="
+ localName
+ ", name="
+ name );
}
for (int i = 0; i < attributes.getLength(); i++) {
if (logger.isInfoEnabled()) {
logger.info("endElement(String, String, String) - uri=" + uri
+ ", localName=" + localName + ", qName=" + attributes.getQName(i)+ ", attributes=" + attributes.getValue(i));
}
}
super.startElement(uri, localName, name, attributes);
}
//對text node的處理
public void characters(char[] ch, int start, int length)
throws SAXException {
if (logger.isInfoEnabled()) {
logger.info("characters(char[], int, int) - ch="+ new String(ch,start,length));
//這里這樣子寫才能得到text node 真正的值。范圍:
characters()
事件不僅包括不僅一個字符串。它還包括起始和長度信息。實際上,ch
字符數組包括整個文檔。應用程序一定不能嘗試讀取饋送給 characters()
事件的范圍之外的字符。
}
super.characters(ch, start, length);
}