Parsing XML files in Android development using the pull Method

Source: Internet
Author: User
Pull Mode

In addition to using Sax and Dom to parse XML files, you can also use the android built-in pull parser to parse XML files. The Running Method of the pull parser is similar to that of the SAX Parser. It is also triggered by events. The pull parsing method allows the application to completely control how the document is parsed. For example, to start and end element events, you can use parser. Next () to enter the next element and trigger corresponding events. The parser. geteventtype () method is used to obtain the code value of the event. parsing completes most of the processing at the beginning. The event is sent as a numeric code, so you can use a switch to process the event you are interested in.

Pull Parsing is a process of traversing documents. Every time you call next (), nexttag (), nexttoken (), and nexttext (), the document is pushed forward and parser stays on some events, but it cannot be regressed. Set the document to parser.

Android provides APIs that support the pull method, mainly

Org. xmlpull. v1.xmlpullparser;

Org. xmlpull. v1.xmlpullparserfactory;

Xmlpullparser and xmlpullparserfactory are used to build xmlpullparser objects.

The application generates an event by calling xmlpullparser. Next () and other methods, and then processes the event.

We still use part of the XML file for the preceding weather forecast as an example.

For example, the XML file to be parsed is:

[Java]

<Forecast_conditions>

<Day_of_week DATA = "Wednesday"/>

<Low data = "22"/>

<High data = "29"/>

<Icon DATA = "/IG/images/weather/chance_of_rain.gif"/>

<Condition data = "rain may exist"/>

</Forecast_conditions>

In these XML files, day_of_week, low, and high are tags, and data is attributea. Of course, if there is <> </> between the start and end symbols, it is txet.

To parse the document, you must first construct an xmlpullparser object.

[Java]

Final xmlpullparserfactory factory = xmlpullparserfactory. newinstance ();

Factory. setnamespaceaware (true );

Final xmlpullparser parser = factory. newpullparser ();

Parser. setinput (New stringreader ("xmlstr ");

Xmlstr is the XML file above.

At this point, the document has just been initialized, so it should be at the beginning of the document. The event is start_document, which can be obtained through xmlpullparser. geteventtype. Then call next () to generate

Start_tag. This event tells the application that a tag has started. When getname () is called, "day_of_week" is returned. If there is text, next () will generate a text event, calling gettext () will return text. Because there is no text here, next () will generate an end_tag, which tells you that a tag has been processed and next () end_document will be generated until the tag is finally processed, which tells you that the entire document has been processed. Except for next ()
Nexttoken () can also be used, but it will return more detailed events, such as comment, cdsect, docdecl, entity and so on. If the program gets the underlying information, you can use nexttoken () to drive and process detailed events. Note that text events may return blank white spaces, such as line breaks or spaces.

Nexttag () -- will ignore white spaces. If you can determine the next one is start_tag or end_tag, you can call nexttag () to directly jump over. Generally, it has two functions: When start_tag, if you can determine that this tag contains a sub-tag, you can call nexttag () to generate the start_tag event of the sub-tag; When end_tag, if it is not the end of the document, you can call nexttag () to generate the start_tag of the next tag. In both cases, if next () is used, a text event is generated, but a line break or blank space character is returned.

Nexttext () -- can only be called when start_tag is used. When the next element is text, the content of text will be returned. When the next element is end_tag, that is, the content of this label is null, then the Null String is returned. After this method is returned, parser stops at end_tag.

The core code is as follows:

[Java]

Mypull. setonclicklistener (New button. onclicklistener (){

@ Override

Public void onclick (view v ){

Try {

String url = "http://www.google.com/ig/api? & Weather = Beijing ";

Defaulthttpclient client = new defaulthttpclient ();

Httpurirequest Req = new httpget (URL );

Httpresponse resp = client.exe cute (req );

Httpentity ent = resp. getentity ();

Inputstream stream = Ent. getcontent (); // imports the file into the stream. Therefore, inputstream is used.

Xmlpullparserfactory factory = xmlpullparserfactory. newinstance ();

Factory. setnamespaceaware (true );

Xmlpullparser xpp = factory. newpullparser ();

Xpp. setinput (stream, null );

// Xpp. setinput (New stringreader ("<Foo> Hello world! </Foo> "));

Int eventtype = xpp. geteventtype ();

While (eventtype! = Xmlpullparser. end_document ){

If (eventtype = xmlpullparser. start_document ){

System. Out. println ("START document ");

} Else if (eventtype = xmlpullparser. start_tag ){

System. Out. println ("start tag" + xpp. getname ());

If (xpp. getname (). Equals ("high ")){

J ++;

If (j = 2 ){

Highesttmp. settext (string. valueof (integer. parseint (xpp. getattributevalue (0)-32) * 5/9 ));

}

}

} Else if (eventtype = xmlpullparser. end_tag ){

System. Out. println ("end tag" + xpp. getname ());

} Else if (eventtype = xmlpullparser. Text ){

System. Out. println ("text" + xpp. gettext ());

}

Eventtype = xpp. Next ();

}

System. Out. println ("end document ");

}

Catch (exception e ){

E. printstacktrace ();

}

}

});

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.