XML之SAX的解析

前端之家收集整理的这篇文章主要介绍了XML之SAX的解析前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
XML: <?xml version="1.0" encoding="GB2312"?> <RESULT> <VALUE>    <NO>A1234</NO>    <ADDR>四川省XX县XX镇XX路X段XX号</ADDR> </VALUE> <VALUE>   <NO>B1234</NO>    <ADDR>四川省XX市XX乡XX村XX组</ADDR> </VALUE> </RESULT> java: package www.yq.com.src; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Stack; import javax.xml.parsers.ParserConfigurationException; 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.XMLReader; import org.xml.sax.helpers.DefaultHandler; public class MyXmlReader extends DefaultHandler{ Stack tags = new Stack(); public static void main(String[] args) { File f = new File("E:\\qi.xml"); SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); SAXParser parser; try { parser = saxParserFactory.newSAXParser(); MyXmlReader handler = new MyXmlReader(); parser.parse(f,handler); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void characters(char[] ch,int start,int length) throws SAXException { super.characters(ch,start,length); String tag = (String) tags.peek(); if(tag.equals("NO")){ System.out.println("--------------"); System.out.println("车牌号:"+new String(ch,length)); } if(tag.equals("ADDR")){ System.out.println("--------------"); System.out.println("车牌地址:"+ new String(ch,length)); } } @Override public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException { super.startElement(uri,localName,qName,attributes); tags.push(qName); } }

猜你在找的XML相关文章