使用JAXP 对 XML文档进行 SAX解析:
1 public class Demo1 { 2 3 /** 4 * 使用JAXP对XML文档进行SAX解析 5 * @throws Exception 6 * @throws ParserConfigurationException 7 */ 8 public static void main(String[] args) throws ParserConfigurationException, Exception { 9 10 //1.创建解析工厂 11 SAXParserFactory factory = SAXParserFactory.newInstance(); 12 13 //2.得到解析器 14 SAXParser sp = factory.newSAXParser(); 15 16 //3.得到读取器 17 XMLReader reader = sp.getXMLReader(); 18 19 //4.设置内容处理器 20 ListHandler handler = new ListHandler(); 21 reader.setContentHandler(handler); 22 23 //5.读取XML文档内容 24 reader.parse("src/book.xml"); 25 } 26 27 } 28 29 //得到XML文档所有内容 30 class ListHandler implements ContentHandler { 31 32 @Override 33 public void startElement(String uri, String localName, String qName, 34 Attributes atts) throws SAXException { 35 System.out.println("<" + qName + ">"); 36 37 //打印标签的属性 38 for(int i = 0;atts != null && i<atts.getLength();i++) { //防止某些时候属性值为空时,抛异常 所以再加个条件atts != null 39 String attName = atts.getQName(i); 40 String attValue = atts.getValue(i); 41 System.out.println(attName + "=" + attValue); 42 } 43 44 } 45 46 @Override 47 public void characters(char[] ch, int start, int length) 48 throws SAXException { 49 System.out.println(new String(ch,start,length)); 50 51 } 52 53 @Override 54 public void endElement(String uri, String localName, String qName) 55 throws SAXException { 56 System.out.println("</" + qName + ">"); 57 58 } 59 60 @Override 61 public void setDocumentLocator(Locator locator) { 62 63 } 64 65 66 67 68 @Override 69 public void startDocument() throws SAXException { 70 // TODO Auto-generated method stub 71 72 } 73 74 @Override 75 public void endDocument() throws SAXException { 76 // TODO Auto-generated method stub 77 78 } 79 80 @Override 81 public void startPrefixMapping(String prefix, String uri) 82 throws SAXException { 83 // TODO Auto-generated method stub 84 85 } 86 87 @Override 88 public void endPrefixMapping(String prefix) throws SAXException { 89 // TODO Auto-generated method stub 90 91 } 92 93 94 @Override 95 public void ignorableWhitespace(char[] ch, int start, int length) 96 throws SAXException { 97 // TODO Auto-generated method stub 98 99 } 100 101 @Override 102 public void processingInstruction(String target, String data) 103 throws SAXException { 104 // TODO Auto-generated method stub 105 106 } 107 108 @Override 109 public void skippedEntity(String name) throws SAXException { 110 // TODO Auto-generated method stub 111 112 } 113 114 }