Android advanced 2: parsing XML using the sax Method

Source: Internet
Author: User

<1> Introduction

What is sax? I used to only hear about Sax and sax, but I never touched it. I want to take a note today.

Sax is short for Simple API for XML. It is both an interface and a package.

Sax isXML parser with high resolution speed and low memory usageAnd is suitable for Android and other mobile devices. Unlike Dom parsing, Dom puts all data into memory for parsing.

The event-driven method is used to parse XML files. That is to say, it does not need to parse the entire document.In the process of parsing documents in order of content, Sax will judge whether the characters currently read are a part of the legal XML syntax. If yes, the event will be triggered. The so-called events are actually some callback methods defined in the contenthandler interface.

Another point is:After obtaining the required information during the parsing processResolution can be terminated at any timeDoes not have to wait until all files are parsed.

Advantages and disadvantages: sax uses stream processing. When a tag is encountered, it does not record the previously encountered tag, that is, when processing a tag, for example, in the startelement method, the information obtained is the Tag Name and attribute. As for the nested structure inside the tag, information related to its structure, such as the upper-layer label, lower-layer label, and the name of its brother node, is unknown. In fact, the structure information of the XML file is lost. If you need this information, you can onlyProgram. Therefore, compared with Dom, it is not convenient for Sax to process XML documents, and the process of sax processing is more complex than Dom.

<2>Common contenthandler Interfaces

Startdocument ()

When a document starts, call this method to perform preprocessing.
Enddocument ()

In contrast to the above method, when the document ends, you can call this method to do some aftercare work.
Startelement (string namespaceuri, string localname, string QNAME, attributes ATTS)

This method is triggered when a start tag is read. Namespaceuri is the namespace, localname is the tag name without the namespace prefix, and QNAME is the tag name with the namespace prefix. You can use ATTS to obtain all the attribute names and corresponding values. It should be noted that an important feature of Sax is its stream processing. When a tag is encountered, it will not record the previously encountered
All the information you know in the startelement () method is the name and attribute of the tag. As for the nested structure of the tag, the name of the Upper-layer tag, it is unknown whether there are sub-Meta and other information related to the structure, and you need your program to complete it. This makes it easier to program and process sax than Dom.
Endelement (string Uri, string localname, string name)

This method corresponds to the above method and calls this method when an end tag is encountered.
Characters (char [] CH, int start, int length)

This method is used to process the content read in the XML file. For example, <Name> xiaosi </Name> is used to obtain the value in the name tag.

The first parameter is used to store the file content. The next two parameters are the start position and length of the read string in this array.
String (CH, start, length) to obtain the content.

<? XML version = "1.0"?> ---------->Startdocument ()

<Student> ---------->Startelement

<Name> ---------->Startelement

Xiasoi ---------->Characters

</Name> ---------->Endelement

<ID>
---------->Startelement

090105 ---------->Characters

</ID> ---------->Endelement

</Student>--------->Endelement

Document ended --------->Startdocument ()


<3> resolution steps

Follow these steps to parse an XML file by using sax:
1. Create a saxparserfactory object (it is easy to know through the class name that it is implemented using the factory method mode );
2. Call the newsaxparser method in saxparserfactory to create a saxparser object;
3. Call the getxmlreader method in saxparser to obtain an xmlreader object;
4. register the event processing interface in xmlreader, which can be contenthandler, errorhandler, dtdhandler, and entityhandler;
5. Call the parse method in xmlreader to parse the specified XML string object;

Specific implementation:

note : contenthandler is an interface and is inconvenient to use, all methods need to be implemented, but some methods will not be used. Therefore, Sax has developed a helper class for it: defaulthandler, which implements this interface, but all its methods are empty. During implementation, you only need to inherit this class and then reload the corresponding method

Package xiaosi. sax; </P> <p> Import Java. io. ioexception; <br/> Import Java. io. stringreader; </P> <p> Import javax. XML. parsers. parserconfigurationexception; <br/> Import javax. XML. parsers. saxparserfactory; </P> <p> Import Org. apache. HTTP. httpresponse; <br/> Import Org. apache. HTTP. client. httpclient; <br/> Import Org. apache. HTTP. client. methods. httpget; <br/> Import Org. apache. HTTP. impl. client. defaulthttpclient; <br/> Import Org. apache. HTTP. protocol. HTTP; <br/> Import Org. apache. HTTP. util. entityutils; <br/> Import Org. XML. sax. inputsource; <br/> Import Org. XML. sax. saxexception; <br/> Import Org. XML. sax. xmlreader; </P> <p> Import android. app. activity; <br/> Import android. OS. bundle; <br/> Import android. view. view; <br/> Import android. view. view. onclicklistener; <br/> Import android. widget. button; </P> <p> public class xmlsaxactivity extends activity <br/>{< br/> private buttonbutton = NULL; <br/> private stringxmlcontent = ""; </P> <p> @ override <br/> Public void oncreate (bundle savedinstancestate) <br/>{< br/> super. oncreate (savedinstancestate); <br/> setcontentview (R. layout. main); <br/> button = (button) findviewbyid (R. id. button); <br/> button. setonclicklistener (New onclicklistener () {<br/> @ override <br/> Public void onclick (view V) <br/>{< br/> try <br/> {<br/> getweatherarray ("Beijing"); <br/> saxparserfactory saxfactory = saxparserfactory. newinstance (); <br/> xmlreader = saxfactory. newsaxparser (). getxmlreader (); <br/> xmlreader. setcontenthandler (New mycontenthandler ()); <br/> string xml = "<student> <Name> xiaosi </Name> <ID> 090105 </ID> </student>"; <br/> xmlreader. parse (New inputsource (New stringreader (XML); <br/>}< br/> catch (saxexception e) <br/>{< br/> E. printstacktrace (); <br/>}< br/> catch (parserconfigurationexception e) <br/>{< br/> E. printstacktrace (); <br/>}< br/> catch (ioexception e) <br/>{< br/> E. printstacktrace (); <br/>}< br/> catch (exception e) <br/>{< br/> E. printstacktrace (); <br/>}< br/>}); <br/>}< br/>

mycontenthandler:

Package xiaosi. sax; </P> <p> 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 mycontenthandler extends defaulthandler <br/> {<br/> stringtag = "xiaosi "; </P> <p> @ override <br/> Public void startdocument () throws saxexception <br/>{< br/> log. I (TAG, "startdocument"); <br/>}</P> <p> @ override <br/> Public void startelement (string Uri, string localname, string QNAME, attributes attributes) throws saxexception <br/>{< br/> log. I (TAG, "startelement"); <br/>}</P> <p> @ override <br/> Public void characters (char [] CH, int start, int length) throws saxexception <br/>{< br/> log. I (TAG, "characters"); <br/>}</P> <p> @ override <br/> Public void enddocument () throws saxexception <br/>{< br/> log. I (TAG, "enddocument"); <br/>}</P> <p> @ override <br/> Public void endelement (string Uri, string localname, string QNAME) throws saxexception <br/>{< br/> log. I (TAG, "endelement"); <br/>}< br/>


Related Article

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.