package cn.itcast.jaxp.sax; import java.io.IOException; 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.helpers.DefaultHandler; /** * XML解析之SAX * @author Lynch * */ public class SAXTest { public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { retrieve(); } /** * 查詢節點 * @throws SAXException * @throws ParserConfigurationException * @throws IOException */ public static void retrieve() throws ParserConfigurationException, SAXException, IOException { // 創建解析器工廠 SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); // 創建解析器 SAXParser saxParser = saxParserFactory.newSAXParser(); // 解析文檔,同時綁定Handler saxParser.parse("src/book.xml", new MyDefaultHandler()); } } class MyDefaultHandler extends DefaultHandler { @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { System.out.print("<" + qName + ">"); } @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 { System.out.print(new String(ch, start, length)); } }
JAXP之SAX解析
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.