Android学习-Sax解析XML

XML解析


XML可扩展标记语言


Sax:

事件驱动型解析接口

原理
对文档顺序扫描,对事件驱动的解析过程,

事件

 开始解析

       开始解析根标签

          开始解析标签

                解析到数据

         结束解析标签

     结束解析根标签

结束解析

工厂模式

SaxParserFactory->SaxParser->SaxReader


核心代码

Stringstr ="<doc><p>test</p></doc>";

SAXParserFactoryfatory =SAXParserFactory.newInstance();

try{

XMLReader reader = fatory.newSAXParser().getXMLReader();

reader.setContentHandler(newXmlHandler());

reader.parse(newInputSource(newStringReader(str)));

}catch(Exception e) {

//TODOAuto-generated catch block

e.printStackTrace();

}




classXmlHandlerextendsDefaultHandler

{


@Override

publicvoidcharacters(char[]ch,intstart,intlength)throwsSAXException {

//TODOAuto-generated method stub

Log.i("","------------characters:"+newString (ch));

}


@Override

publicvoidendDocument()throwsSAXException {

//TODOAuto-generated method stub

Log.i("","------------endDocument");

}


@Override

publicvoidendElement(String uri, String localName, String qName) throwsSAXException {

//TODOAuto-generated method stub

Log.i("","------------endElement");

}


@Override

publicvoidstartDocument()throwsSAXException {

Log.i("","------------startDocument");

}


@Override

publicvoidstartElement(String uri, String localName, String qName, Attributesattributes) throwsSAXException {

Log.i("","------------startElement");

}

}



posted on 2016-08-07 12:37  记住我叫王凯  阅读(196)  评论(0编辑  收藏  举报

导航