Android Parsing XML method (ii)

Source: Internet
Author: User
Tags call back tagname

In the previous section, we used the DOM method to parse the XML document, which is easier to use in our everyday thinking, but it directly puts the document into memory and consumes more memory. Here we can parse the XML in a different way, this is the sax way.

Sax is: Simple API for XML

Sax is event-driven. Of course, the event mechanism of Android is based on callback function, when parsing XML document with sax, when reading to the beginning of the document and the end of the tag callback an event, when reading to other nodes and content will also callback an event.

Since the event is involved, there is the event source, the event handler. In the Sax interface, the event source is the XmlReader in the Org.xml.sax package, which parses the XML document and generates events through the parser () method. The event handlers are the 4 interfaces of Contenthander, Dtdhander, ErrorHandler, and Entityresolver in the Org.xml.sax package

XmlReader the connection to the 4 interfaces of Contenthander, Dtdhander, ErrorHandler, and entityresolver through the corresponding event processor registration method Setxxxx (), see the following table for details:

But we do not have to inherit these 4 interfaces, the SDK provides us with the DefaultHandler class to handle, some of the main event callback methods of the DefaultHandler class are as follows:

From the above, we need XmlReader and DefaultHandler to parse the XML together.

The process of thinking is:

1: Create a SAXParserFactory object

2: Returns a SAXParser parser based on the Saxparserfactory.newsaxparser () method
3: Get event source object based on SAXParser parser XmlReader
4: Instantiate a DefaultHandler object

5: Connect Event Source object XmlReader to event-handling class DefaultHandler

6: Call the Parse method of XmlReader to get the XML data from the input source

7: Return the data collection we need through DefaultHandler.

The code is as follows:

Public list<river> Parse (String xmlpath) {list<river> rivers=null;        SAXParserFactory factory=saxparserfactory.newinstance ();            try {saxparser parser=factory.newsaxparser ();            Get Event Source XMLReader Xmlreader=parser.getxmlreader ();            Set Processor Riverhandler handler=new Riverhandler ();            Xmlreader.setcontenthandler (handler);            Parses the XML document//xmlreader.parse (new InputSource (New URL (Xmlpath). OpenStream ()));            Xmlreader.parse (New InputSource (This.context.getAssets (). Open (Xmlpath)));            Rivers=handler.getrivers ();        } catch (Parserconfigurationexception e) {//TODO auto-generated catch block E.printstacktrace ();        } catch (Saxexception e) {//TODO auto-generated catch block E.printstacktrace ();        } catch (IOException e) {e.printstacktrace ();    } return rivers; }

  

The focus is on the DefaultHandler object for each element node, attribute, text content, document content to be processed.

As I said earlier, DefaultHandler is based on the event-handling model, and the basic approach is to call back the Startdocument method when the SAX parser navigates to the document start tag, and the Enddocument method when navigating to the document end tag. Callback the Startelement method when the SAX parser navigates to the start tag of an element, navigates to its text content when the callback characters method navigates to the end of the label callback EndElement method.

Based on the above explanations, we can draw the following processing of the XML document logic:

1: When navigating to the document start tag, in the callback function startdocument, you can not do processing, of course, you can verify the next UTF-8 and so on.

2: When navigating to the rivers start tag, a collection can be instantiated in the callback method startelement to store the list, but we don't need it here because it's already instantiated in the constructor.

3: When navigating to the river start tag, it means that the river object needs to be instantiated, and of course the river tag also has the NAME, length property, so the attribute value must also be fetched after the river is instantiated, Attributes.getvalue (NAME), Also adds a Boolean-true identity to the river tag that you navigate to when you add it to the river object, to indicate that you have navigated to the river element.

4: Of course there are sub-tags (nodes) inside the river tag, but the SAX parser does not know what to navigate to, it only knows the beginning and the end. So how do we make it recognize our labels? Of course you need to judge, so you can use the callback method startelement parameter string localname, our tag string and this parameter comparison, it is possible. We also have to let sax know that it is now navigating to a tag, so adding a true property lets the SAX parser know. So

5: It will also navigate to the text inside the label, (that is, the contents of the </img>), callback method characters, we generally take out in this method is the contents of </img>, and save.

6: Of course it is sure to navigate to the end tag </river> or </rivers>, if it is a </river> tag, remember to add the river object into the list. If the sub-label in the river is </introduction>, the Boolean flag that navigates to the tag in front of the setting tag is set to False.

According to the implementation of the above ideas, you can implement the following code:

/** navigate to start tag trigger **/public void startelement (string uri, String localname, String qName, Attributes Attributes) {         String tagname=localname.length ()!=0?localname:qname;         Tagname=tagname.tolowercase (). Trim ();             If you are reading the river label start, instantiate the river if (tagname.equals) {isriver=true;                River=new River ();                /** navigates to the river Start node **/river.setname (Attributes.getvalue (NAME));         River.setlength (Integer.parseint (Attributes.getvalue (LENGTH))); }//Then read other node if (isriver) {if (Tagname.equals (INTRODUCTION)) {xintroduction=t             Rue             }else if (tagname.equals (IMAGEURL)) {ximageurl=true; }}}/** navigate to the end tag trigger **/public void endElement (string uri, string localname, Strin         G qName) {String tagname=localname.length ()!=0?localname:qname;         Tagname=tagname.tolowercase (). Trim ();        If you read the river label end, add the river to the set if (Tagname.equals (river)) {isriver=true;         Rivers.add (river); }//Then read other node if (isriver) {if (Tagname.equals (INTRODUCTION)) {xintroduction=f             Alse;             }else if (tagname.equals (IMAGEURL)) {ximageurl=false; }}}//This is the time to read to the node content when callback public void characters (char[] ch, int start, int length {//Set property value if (xintroduction) {//resolve null problem River.setintrod                 Uction (River.getintroduction () ==null? "": River.getintroduction () +new String (ch,start,length)); }else if (ximageurl) {//Resolve null Problem River.setimageurl (River.getimageurl () ==null? "": Riv                 Er.getimageurl () +new String (ch,start,length)); }            }

The results of the operation are as follows:

Android Parsing XML method (ii)

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.