Parsing XML using Android pull

Source: Internet
Author: User

.

Code structure:

Let's take a look at the Code:

Main. xml

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" <br/> Android: Orientation = "vertical" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "fill_parent" <br/> <textview <br/> Android: id = "@ + ID/showbeauty" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "wrap_content" <br/> </linearlayout> <br/>

Activity Code

Package cn.com. pulltest; </P> <p> Import Java. io. inputstream; <br/> Import Java. util. arraylist; </P> <p> Import Org. xmlpull. v1.xmlpullparser; <br/> Import Org. xmlpull. v1.xmlpullparserfactory; </P> <p> Import android. app. activity; <br/> Import android. OS. bundle; <br/> Import android. util. log; <br/> Import android. widget. textview; </P> <p> public class pullactivity extends activity {<br/> private string result = ""; <Br/> private arraylist <beauty> beauties = new arraylist (); <br/> @ override <br/> Public void oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); <br/> setcontentview (R. layout. main); <br/> try {<br/> // obtain the XML file in the src directory as a stream (the parent folder of this file must be SRC) <br/> inputstream = This. getclass (). getclassloader (). getresourceasstream ("beauties. XML "); <br/> // get an xmlpullparser <br/> Xmlpullparserfactory = xmlpullparserfactory. newinstance (); <br/> xmlpullparser parser = xmlpullparserfactory. newpullparser (); <br/> // sets the encoding mode of the input stream. <br/> parser. setinput (inputstream, "UTF-8"); <br/> // get the current event type <br/> int eventtype = parser. geteventtype (); <br/> Beauty = NULL; <br/> while (xmlpullparser. end_document! = Eventtype) {<br/> string nodename = parser. getname (); </P> <p> switch (eventtype) {<br/> case xmlpullparser. start_tag: <br/> If (nodename. equals ("beauty") {<br/> beauty = new beauty (); <br/>}< br/> If (nodename. equals ("name") {<br/> beauty. setname (parser. nexttext (); <br/>}< br/> If (nodename. equals ("Age") {<br/> beauty. setage (parser. nexttext (); <br/>}< br/> break; </P> <p> case xmlpullparser. end_tag: <br/> If (Nodename. Equals ("beauty") & Beauty! = NULL) {<br/> beauties. add (beauty); <br/>}</P> <p> break; <br/> default: <br/> break; <br/>}< br/> // manually trigger the next event <br/> eventtype = parser. next (); <br/> log. I ("pullactivity", eventtype + ""); <br/>}</P> <p> for (beauty beauty2: beauties) {<br/> result + = "/N" + beauty2.tostring (); <br/>}< br/> // result = beauties. size () + ""; <br/> textview = (textview) findviewbyid (R. id. showbeauty); <br/> textview. settext ("final result:/N" + result); </P> <p >}catch (exception e) {<br/> E. printstacktrace (); <br/>}</P> <p >}< br/>/** <br/> * @ author chenzheng <br/> * used here internal classes are for efficiency consideration, internal classes are more efficient and space-saving than single bean classes <br/> */<br/> private class beauty {<br/> string name; <br/> string age; <br/> Public String getname () {<br/> return name; <br/>}< br/> Public void setname (string name) {<br/> This. name = Name; <br/>}< br/> Public String getage () {<br/> return age; <br/>}< br/> Public void setage (string age) {<br/> This. age = age; <br/>}< br/> @ override <br/> Public String tostring () {<br/> return "Beauty information [age =" + age + ", name =" + name + "]"; <br/>}</P> <p>}

 

Beauties. xml

<? XML version = "1.0" encoding = "UTF-8"?> </P> <p> <beauties> </P> <p> <beauty> </P> <p> <Name> Lin Zhiling </Name> </P> <p> <age> 28 </age> </P> <p> </beauty> </P> <p> <name> Yang Mi </Name> </P> <p> <age> 23 </age> </P> <p> </beauty> </P> <p> </beauties> <br/>

The book. xml here is not used.

Androidmanifest. XML is used by default.

Run, we can see the results at the beginning.

 

Bytes ----------------------------------------------------------------------------------------

 

Beauties. XML location. Here we add another book. XML is also used to make it clear that the exact location of the XML file should be under SRC, rather than the subfolders under SRC.

 

Bytes ----------------------------------------------------------------------------------------

Generally, we use Java to parse XML. There are two main methods: one is sax parsing and the other is Dom parsing. Of course, there are a series of other third-party parsing APIs, such as JDOM/dom4j. They have their respective advantages and disadvantages. Here we mainly analyze the two most basic parsing methods, namely, Sax parsing and Dom parsing.

The resolution mechanisms of the two dependencies are completely different. Sax parsing depends on the event trigger mechanism. You can think that when we read XML, Each XML content will trigger the corresponding event. When we read one row, the event will alsoAutomaticTrigger one by one until the final end. In the code, we need to implement a defaulthandler to define what operations are performed when XML reads something. You can only keep reading The End Of The documentation header for Sax parsing. You cannot stop or modify the file in the middle. It will not be returned until the entire document is parsed.

Dom parsing completes XML parsing by forming a node tree in the memory. Although it can quickly locate a location in XML and modify it, however, it requires a large amount of memory. Especially when the XML file is large, this disadvantage is even more serious. This is fatal for mobile phones.

The feature of the sax method is that a complete document needs to be parsed before it is returned. If we only need the previous part of data in an XML document, the whole document will still be parsed using the sax method, although we do not need to parse most of the data behind the XML document, this actually wastes processing resources.

To solve this problem, Android uses another more efficient and convenient XML parsing method to parse XML files, which is pull parsing.

The pull parser and the SAX Parser have differences but similarities. The difference is that the SAX Parser automatically pushes events to the registered event processor for processing, so you cannot control the event processing to take the initiative to end; the working method of the pull parser allows you to actively retrieve events from the parser in application code, because the events are actively obtained, therefore, after meeting the required conditions, you can stop obtaining the event and complete the parsing.


In the ophone/Android system, the package related to the PULL mode is Org. xmlpull. v1: The factory class xmlpullparserfactory and pull parser of the pull parser are provided in this package. The xmlpullparserfactory instance calls the newpullparser method to create an xmlpullparser parser instance, then, the xmlpullparser instance can call methods such as geteventtype () and next () to actively extract events and perform logical Processing Based on the extracted event types.

The Code is as follows:

// Obtain the XML file in the src directory as a stream (the parent folder of this file must be SRC) <br/> inputstream = This. getclass (). getclassloader (). getresourceasstream ("beauties. XML "); <br/> // get an xmlpullparser <br/> xmlpullparserfactory = xmlpullparserfactory. newinstance (); <br/> xmlpullparser parser = xmlpullparserfactory. newpullparser (); <br/> // sets the encoding mode of the input stream. <br/> parser. setinput (inputstream, "UTF-8 ");

Then we can use the method provided in xmlpullparser for parsing. Here we will list several important methods.

// Call the API at the beginning of XML reading and trigger the first event when reading the file. The returned event ID is

Public int geteventtype () throws xmlpullparserexception;

// Traverse the next event and return the type of an event

Public int next () throws xmlpullparserexception, ioexception

// Obtain the current Tag Name

Public String getname ();

// Obtain text

Public String gettext ();

// Obtain the number of attributes under the current tag

Public int getattributecount ();

// Obtain the attribute name at the specified position under the current tag

Public String getattributename (INT index );

// Obtain the attribute planting at the specified position under the current tag

Public String getattributevalue (INT index );

 

// If the current event is a start_tag and the next element is text, the text content will be returned. If the next element is end_tag, an empty string will be returned for a long time; in other cases, an exception is returned.

Public String getnexttext ();

-------------------------------------------------------------------------

Let's summarize the code steps for pull parsing:

Step 1: first define an XML file (of course, it can also be an XML file obtained from the Network)

Step 2: Create an xmlpullparser object for File Parsing

Step 3: Associate the file with the file parser using the parser. setinput () method.

Step 4: Call geteventtype (); The method starts parsing.

Step 5: Process XML in the WHILE LOOP

 

 

 

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.