事件驱动方式的解析
package com.gyarmy.sax; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; /* * 结论: * 碰到实现接口中的方法,但是只有很少的方法和我们有关时,去找默认的实现类 * * */ public class SaxTest1 { public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { // TODO Auto-generated method stub //拿到工厂 SAXParserFactory factory = SAXParserFactory.newInstance(); //拿到解析器对象 SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(new MyContentHandler()); //去解析 XML文件 reader.parse("src/demo1.xml"); } } class MyContentHandler extends DefaultHandler{ //重写目标方法 //alt + shift + S //选择重写的方法 //定义boolean值 和 计数器,是非常常规的小技巧 protected int i=0; @Override public void startDocument() throws SAXException { // TODO Auto-generated method stub //System.out.println("文档开始"); } @Override public void endDocument() throws SAXException { // TODO Auto-generated method stub //System.out.println("文档结束"); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // TODO Auto-generated method stub //System.out.println("元素开始:"+qName); if(qName == "售价") { //endElement(); i = 1; //System.out.println(attributes.get); //return; } /* for(int i=0;i<attributes.getLength();i++) { String name = attributes.getQName(i); String value = attributes.getValue(i); System.out.println(i + "--" + name+":"+value); } */ } @Override public void endElement(String uri, String localName, String qName) throws SAXException { // TODO Auto-generated method stub if(qName == "售价") { i = 0; } //System.out.println("元素结束:"+qName); } @Override public void characters(char[] ch, int start, int length) throws SAXException { // TODO Auto-generated method stub if(i == 1) { System.out.println(new String(ch,start,length)); } } }
0则评论给“JAVA操作XML文件 - SAX操作”