Android improves XML parsing and generation in Article 7

Source: Internet
Author: User

This article from http://blog.csdn.net/hellogv/, reference must indicate the source!

In this article, we use SAX to parse XML. In Android, we can use SAX and Dom. Dom needs to read the entire XML file into the memory and parse it, which consumes a lot of memory. However, Sax is based on event-driven processing methods, callback functions can be triggered on each node. However, Sax is suitable for XML documents with simple node structures. Complex XML documents may be difficult to process in the future.

The test. xml file to be parsed in this article is as follows:

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <Test> <br/> <title> testsax </title> <br/> <content AA = "1" BB = "2"> <br/> <Name> hellogv </Name> <br/> <URL> http://blog.csdn.net/hellogv </URL> <br/> </content> <br/> </test> 

The result of parsing the above XML is as follows:

 

To use SAX parsing, You need to define saxparserfactory (so that the application can configure and obtain a sax-based parser to parse XML documents), saxparser (Parse XML from various input sources ), xmlreader (read XML documents using callback functions), among which xmlreader is critical. Xmlreader can define various callback functions for parsing XML. These callback functions are triggered when the conditions are met.

Saxparserfactory factory = saxparserfactory. newinstance (); <br/> saxparser parser = factory. newsaxparser (); <br/> xmlreader reader = parser. getxmlreader (); <br/> reader. setcontenthandler (handler); <br/> reader. parse (New inputsource (testsax. this. getresources () <br/>. openrawresource (R. raw. test )));

In this Code, xmlreader calls the saxhandler that inherits defaulthandler. Defaulthandler has implemented contenthandler, dtdhandler, entityresolver, errorhandler and Other interfaces, including common XML reading operations. For details, see the following saxhandler. Java source code.

The XML generation result is as follows:

After reading each node, use xmlserializer to re-combine and output the XML string.

The main. XML code in this article is as follows:

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" <br/> Android: Orientation = "vertical" Android: layout_width = "fill_parent" <br/> Android: layout_height = "fill_parent"> </P> <p> <button Android: layout_height = "wrap_content" <br/> Android: layout_width = "fill_parent" Android: id = "@ + ID/btnsax" <br/> Android: text = "using Sax to parse XML"> </button> <br/> <button Android: layout_height = "wrap_content" <br/> Android: layout_width = "fill_parent" Android: text = "XML" Android: id = "@ + ID/btnoutput"> </button> <br/> <edittext Android: text = "@ + ID/edittext01" Android: id = "@ + ID/edittext01" <br/> Android: layout_width = "fill_parent" Android: layout_height = "fill_parent"> </edittext> </P> <p> </linearlayout> <br/>

The source code of saxhandler. Java is as follows:

Package COM. testsax; </P> <p> Import Java. util. arraylist; <br/> Import Org. XML. sax. attributes; <br/> Import Org. XML. sax. saxexception; <br/> Import Org. XML. sax. helpers. defaulthandler; </P> <p> Import android. util. log; </P> <p> public class saxhandler extends defaulthandler {<br/> private arraylist <string> keys = new arraylist <string> (); // Save the field name <br/> private arraylist <Object> values = new arraylist <Object> (); // Save the value <br/> @ override <br/> Public void startdocument () throws saxexception {<br/> super. startdocument (); </P> <p >}</P> <p> @ override <br/> Public void enddocument () throws saxexception {<br/> super. enddocument (); <br/>}</P> <p> @ override <br/> Public void startelement (string Uri, string localname, string QNAME, <br/> attributes) throws saxexception {<br/> // save start tag <br/> keys. add ("starttag"); <br/> values. add (localname); </P> <p> log. E ("starttag", localname); <br/> // Save the attribute value <br/> for (INT I = 0; I <attributes. getlength (); I ++) {<br/> keys. add ("ATTR"); <br/> string [] STR = new string [2]; <br/> STR [0] = attributes. getlocalname (I); <br/> STR [1] = attributes. getvalue (I); <br/> values. add (STR); <br/> log. E ("ATTR", STR [0] + "=" + STR [1]); <br/>}</P> <p> @ override <br/> Public void endelement (string Uri, string localname, string QNAME) <br/> throws saxexception {<br/> // Save the end mark <br/> keys. add ("endtag"); <br/> values. add (localname); <br/> log. E ("endtag", localname); <br/>}</P> <p> @ override <br/> Public void characters (char [] CH, int start, int length) <br/> throws saxexception {<br/> string value = new string (CH, start, length); <br/> value = value. trim (); <br/> If (value. length () = 0) <br/> return; </P> <p> keys. add ("text"); <br/> values. add (value); <br/> log. E ("text", value); <br/>}</P> <p> Public arraylist <string> getkeys () <br/>{< br/> return keys; <br/>}</P> <p> Public arraylist <Object> getvalues () <br/>{< br/> return values; <br/>}</P> <p >}< br/>

The source code of testsax. Java is as follows:

Package COM. testsax; </P> <p> Import Java. io. stringwriter; </P> <p> Import javax. XML. parsers. saxparser; <br/> Import javax. XML. parsers. saxparserfactory; </P> <p> Import Org. XML. sax. inputsource; <br/> Import Org. XML. sax. xmlreader; <br/> Import Org. xmlpull. v1.xmlserializer; </P> <p> Import android. app. activity; <br/> Import android. OS. bundle; </P> <p> Import android. util. XML; <br/> Import android. view. view; <br/> Import android. widget. button; <br/> Import android. widget. edittext; </P> <p> public class testsax extends activity {<br/>/** called when the activity is first created. */<br/> button btnsax, btnoutput; <br/> edittext memo; <br/> saxhandler handler = new saxhandler (); </P> <p> @ override <br/> Public void oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); <br/> setcontentview (R. layout. main); <br/> btnsax = (button) This. findviewbyid (R. id. btnsax); <br/> btnsax. setonclicklistener (New clickevent (); <br/> btnoutput = (button) This. findviewbyid (R. id. btnoutput); <br/> btnoutput. setonclicklistener (New clickevent (); <br/> memo = (edittext) This. findviewbyid (R. id. edittext01); </P> <p >}</P> <p> class clickevent implements view. onclicklistener {</P> <p> @ override <br/> Public void onclick (view v) {<br/> If (V = btnsax) {// Parse XML, and save the tag. The attribute is equivalent to <br/> try {<br/> saxparserfactory factory = saxparserfactory. newinstance (); <br/> saxparser parser = factory. newsaxparser (); <br/> xmlreader reader = parser. getxmlreader (); <br/> reader. setcontenthandler (handler); <br/> reader. parse (New inputsource (testsax. this. getresources () <br/>. openrawresource (R. raw. test); <br/>}catch (exception ee) {}< br/>}< br/> else if (V = btnoutput) {// generate xml <br/> try {<br/> xmlserializer serializer = xml. newserializer (); <br/> stringwriter writer = new stringwriter (); <br/> try {<br/> serializer. setoutput (writer); <br/> serializer. startdocument ("UTF-8", true); </P> <p> for (INT I = 0; I <pandler. getkeys (). size (); I ++) <br/>{< br/> If (handler. getkeys (). get (I ). equals ("starttag") <br/>{< br/> serializer. starttag ("", (string) handler. getvalues (). get (I); <br/>}< br/> else if (handler. getkeys (). get (I ). equals ("ATTR") {<br/> string [] STR = (string []) handler. getvalues (). get (I); <br/> serializer. attribute ("", STR [0], STR [1]); <br/>}< br/> else if (handler. getkeys (). get (I ). equals ("text") <br/> serializer. text (string) handler. getvalues (). get (I); <br/> else if (handler. getkeys (). get (I ). equals ("endtag") <br/>{< br/> serializer. endtag ("", (string) handler. getvalues (). get (I); <br/>}< br/> serializer. enddocument (); <br/> string text = writer. tostring (); <br/> text = text. replace ("> <", ">/R/n <"); <br/> memo. settext (text); // output to the text box <br/>} catch (exception e) {<br/> throw new runtimeexception (E ); <br/>}</P> <p>} catch (exception E) {}< br/>}</P> <p >}< br/>}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.