Android创建与解析XML(三)——详解Sax方式
1. sax概述
sax是一种占用内存少且解析速度快的解析器,它采用的是事件启动,不需要解析完整个文档,而是按照内容顺序看文档某个部分是否符合xml语法,如果符合就触发相应的事件,所谓的事件就是些回调方法(callback),这些方法 定义在contenthandler中,下面是其主要方法:
startdocument():当遇到文档的时候就触发这个事件 调用这个方法 可以在其中做些预处理工作,如:申请对象资源
enddocument():当结束文档的时候就触发这个事件 调用这个方法 可以在其中做些善后工作,如:释放申请的对象资源
startelement(string namespaceuri, string localname, string qname, attributes atts):当遇开始标签的时候就会触发这个方法。
endelement(string uri, string localname, string name):当遇到结束标签时触发这个事件,调用此法可以做些善后工作。
charachers(char [] ch, int start, int length):当遇到xml内容时触发这个方法,用new string(ch,start,length)可以接受内容。
sax方式创建xml,应用了标准xml构造器 javax.xml.transform.sax.transformerhandler 事件来创建 xml 文档,需要导入以下内容
javax.xml.transform
- javax.xml.transform.sax.saxtransformerfactory;
- javax.xml.transform.sax.transformerhandler;
- javax.xml.transform.transformer;
- javax.xml.transform.transformerconfigurationexception;
- javax.xml.transform.transformerfactoryconfigurationerror;
- javax.xml.transform.outputkeys;
- javax.xml.transform.stream.streamresult;
- javax.xml.transform.sax.saxtransformerfactory;
javax.xml.parsers
- javax.xml.parsers.saxparser;
- javax.xml.parsers.saxparserfactory;
- javax.xml.parsers.factoryconfigurationerror;
- javax.xml.parsers.parserconfigurationexception;
org.xml.sax
- org.xml.sax.attributes;
- org.xml.sax.saxexception;
- org.xml.sax.helpers.attributesimpl;
- org.xml.sax.helpers.defaulthandler;
sax 创建和解析 xml 的效果图:
2、sax 创建 xml
首先,saxtransformerfactory.newinstance() 创建一个工厂实例 factory
接着,factory.newtransformerhandler() 获取 transformerhandler 的 handler 对象
然后,通过 handler 事件创建handler.gettransformer()、 handler.setresult(result),以及 startdocument()、startelement、characters、endelement、enddocument()等
/** sax方式,创建 xml */ public string saxcreatexml(){ stringwriter xmlwriter = new stringwriter(); person []persons = new person[3]; // 创建节点person对象 persons[0] = new person(1, "sunboy_2050", "http://blogcsdnnet/sunboy_2050"); persons[1] = new person(2, "baidu", "http://wwwbaiducom"); persons[2] = new person(3, "google", "http://wwwgooglecom"); try { saxtransformerfactory factory = (saxtransformerfactory)saxtransformerfactorynewinstance(); transformerhandler handler = factorynewtransformerhandler(); transformer transformer = handlergettransformer(); // 设置xml属性 transformersetoutputproperty(outputkeysindent, "yes"); transformersetoutputproperty(outputkeysencoding, "utf-8"); transformersetoutputproperty(outputkeysversion, "0"); streamresult result = new streamresult(xmlwriter); // 保存创建的xml handlersetresult(result); handlerstartdocument(); attributesimpl attr = new attributesimpl(); attrclear(); attraddattribute("", "", "author", "", "homer"); attraddattribute("", "", "date", "", "2012-04-27"); handlerstartelement("", "", "root", attr); int personslen = personslength; for(int i=0; i<personslen; i++){ attrclear(); handlerstartelement("", "", "person", attr); attrclear(); handlerstartelement("", "", "id", attr); string id = persons[i]getid() + ""; handlercharacters(idtochararray(), 0, idlength()); handlerendelement("", "", "id"); attrclear(); handlerstartelement("", "", "name", attr); string name = persons[i]getname(); handlercharacters(nametochararray(), 0, namelength()); handlerendelement("", "", "name"); attrclear(); handlerstartelement("", "", "blog", attr); string blog = persons[i]getblog(); handlercharacters(blogtochararray(), 0, bloglength()); handlerendelement("", "", "blog"); handlerendelement("", "", "person"); } handlerendelement("", "", "root"); handlerenddocument(); } catch (transformerfactoryconfigurationerror e) { // saxtransformerfactorynewinstance eprintstacktrace(); } catch (transformerconfigurationexception e) { // factorynewtransformerhandler eprintstacktrace(); } catch (illegalargumentexception e) { // transformersetoutputproperty eprintstacktrace(); } catch (saxexception e) { // handlerstartdocument eprintstacktrace(); } catch (exception e) { eprintstacktrace(); } savedxml(filename, xmlwritertostring()); return xmlwritertostring(); }
运行结果:
3、sax解析xml
/** sax方式,解析 xml */ public string saxresolvexml(){ stringwriter xmlwriter = new stringwriter(); inputstream is = readxml(filename); try { saxparserfactory factory = saxparserfactorynewinstance(); saxparser saxparser = factorynewsaxparser(); personhandler handler = new personhandler(); // person处理handler saxparserparse(is, handler); // handler解析xml // 获取解析的xml string xmlheader = handlergetxmlheader(); xmlwriterappend(xmlheader); list<person> personslist = handlergetpersons(); int personslen = personslistsize(); for(int i=0; i<personslen; i++){ xmlwriterappend(personslistget(i)tostring())append("\n"); } } catch (factoryconfigurationerror e) { // saxparserfactorynewinstance eprintstacktrace(); } catch (parserconfigurationexception e) { // factorynewsaxparser eprintstacktrace(); } catch (saxexception e) { // factorynewsaxparser eprintstacktrace(); } catch (illegalargumentexception e) { // saxparserparse eprintstacktrace(); } catch (ioexception e) { // saxparserparse eprintstacktrace(); } catch (exception e) { eprintstacktrace(); } return xmlwritertostring(); } /** handler处理类 */ private final class personhandler extends defaulthandler{ private list<person> personslist = null; // 保存person private person person = null; private stringbuffer xmlheader; // 保存xml头部信息 private string tag = null; // xml element /** 返回解析的xml头部信息 */ public string getxmlheader(){ return xmlheadertostring(); } /** 返回解析的person实例数组 */ public list<person> getpersons(){ return personslist; } @override public void startdocument() throws saxexception{ superstartdocument(); personslist = new arraylist<person>(); xmlheader = new stringbuffer(); } @override public void startelement(string uri, string localname, string qname, attributes attributes) throws saxexception{ superstartelement(uri, localname, qname, attributes); if("root"equals(localname)) { string attrauthor = attributesgetvalue(0); string attrdate = attributesgetvalue(1); xmlheaderappend("root")append("\t\t"); xmlheaderappend(attrauthor)append("\t"); xmlheaderappend(attrdate)append("\n"); } else if("person"equals(localname)) { person = new person(); } tag = localname; } @override public void characters(char[] ch, int start, int length) throws saxexception { supercharacters(ch, start, length); if (null != tag) { string value = new string(ch, start, length); systemoutprintln("value = " + value); if ("id"equals(tag)) { personsetid(new integer(value)); } else if ("name"equals(tag)) { personsetname(value); } else if ("blog"equals(tag)) { personsetblog(value); } } } @override public void endelement(string uri, string localname, string qname) throws saxexception { if("person"equals(qname)) { personslistadd(person); person = null; } tag = null; superendelement(uri, localname, qname); } @override public void enddocument() throws saxexception{ // personslist = null; superenddocument(); } }
运行结果:
4、person类
请参见前文android 创建与解析xml(二)—— dom方式 【4、person类】
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: 将数据插入到MySQL表中的详细教程
推荐阅读