标签:
1 SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); 2 SAXParser parser = saxParserFactory.newSAXParser(); 3 XMLReader reader = parser.getXMLReader(); 4 reader.setContentHandler(new ContentHandler() { 5 // 开始文档节点 6 public void startDocument() throws SAXException { 7 System.out.println("开始文档节点"); 8 } 9 10 // 结束文档节点 11 public void endDocument() throws SAXException { 12 System.out.println("结束文档节点"); 13 } 14 15 // 开始元素节点 16 @Override 17 public void startElement(String uri, String localName, 18 String qName, Attributes atts) throws SAXException { 19 System.out.println("开始元素节点" + qName); 20 //获取元素的属性操作 21 String data = atts.getValue(0); 22 } 23 24 // 结束元素节点 25 @Override 26 public void endElement(String uri, String localName, String qName) 27 throws SAXException { 28 System.out.println("结束元素节点" + qName); 29 } 30 31 // 获取文本 32 @Override 33 public void characters(char[] ch, int start, int length) 34 throws SAXException { 35 System.out.println(new String(ch, start, length)); 36 } 37 38 //还有几个方法,不常用,空实现..... 39 }); 40 reader.parse("bookstore.xml");
1 reader.setContentHandler(new DefaultHandler() { 2 @Override 3 public void characters(char[] ch, int start, int length) 4 throws SAXException { 5 System.out.println(new String(ch, start, length)); 6 } 7 });
标签:
原文地址:http://www.cnblogs.com/lee-hao/p/4564776.html