package demo; import java.util.Stack; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class MyXMLSAX extends DefaultHandler { //Stack tags=new Stack(); public MyXMLSAX() { super(); } public static void main(String[] args) { long lasting=System.currentTimeMillis(); try { SAXParserFactory factory=SAXParserFactory.newInstance(); SAXParser sp=factory.newSAXParser(); MyXMLSAX ms=new MyXMLSAX(); sp.parse(new InputSource("src/a.xml"), ms); } catch (Exception e) { e.printStackTrace(); } System.out.println("运行时间"+(System.currentTimeMillis()-lasting)+"毫秒"); } @Override public void endDocument() throws SAXException { System.out.println("解析完成"); } @Override public void startDocument() throws SAXException { System.out.println("开始解析"); } public String tmp=null; @Override public void characters(char[] ch, int start, int length) throws SAXException { if(tmp!=null){ // System.out.println("进来了tmp:"+tmp); // for(int i=0;i<ch.length;i++){ // System.out.print(ch[i]); // } // System.out.println(); // System.out.println("--"+start+"---"+length); if(tmp.equals("sname")){ System.out.println(" sname:"+new String(ch, start, length)); } if(tmp.equals("sex")){ System.out.println(" sex:"+new String(ch, start, length)); } if(tmp.equals("age")){ System.out.println(" age:"+new String(ch, start, length)); } } } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { //attributes.getValue()这个方法时读标签里面的属性值,<sname value="哈哈"></sname>,结果就是哈哈,也可以将0换成'value' //System.out.println(qName+":"+attributes.getValue(0)); tmp=qName; System.out.println("开始读取节点:"+qName+"---tmp:"+tmp); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { //如果不设置为null的话,他会把<sname>这个标签前面的空白当值赋给sname,这样sanme就多循环了2次, //切记不要忽略空白,那也是一个节点 //在用Sax解析的时候最需要重视的一点就是不要把那些<节点>之间的空白忽略就好! tmp=null; System.out.println("完成节点读取"+qName+"---tmp:"+tmp); } }