Pull parsing XML for Android network programming
In addition to the SAX and Dom methods described earlier, you can also parse an XML document through pull. The pull parser is parsed in a very similar way to sax. It provides a similar event, using Parser.next () to enter the next element and trigger the event, the event will be sent as a numeric code, so you can use a switch to select the event of interest and then handle it accordingly, calling Parser.nexttext () method to get the value of the next text type element.
Pull Parser Features:
* Simple structure: An interface, an exception, a factory is composed of a pull parser
* Easy to use: only 5 events:
1.start_document---> Start parsing events
2.start_tag---> Start element
3.end_tag---> End element
4.TEXT---> Parsing text
5.end_document---> End parsing events
Look directly at the code:
public class Pullpersonparse {/** * uses pull technology to parse XML * @param instream * @return * @throws throwable */PUBL IC Static arraylist<person> pullparsepersons (InputStream instream) throws Throwable{arraylist<person> persons = NULL; person person = null; Xmlpullparser parser = Xml.newpullparser ();p arser.setinput (instream, "UTF-8"); int eventtype = Parser.geteventtype (); /produces the first event while (eventtype!=xmlpullparser.end_document) {///As long as it is not the end of document resolution event switch (EventType) {case Xmlpullparser.start_ DOCUMENT://begins parsing Event persons = new arraylist<person> (); break;case xmlpullparser.start_tag://start element String name = Parser.getname ();//Gets the name of the element that the parser is currently pointing to if ("person". Equals (name)) {person = new person ();p Erson.setid (New Integer ( Parser.getattributevalue (0)));} if (person!=null) {if ("name". Equals (name)) {Person.setname (Parser.nexttext ());//Gets the value of the next text node that the parser currently points to the element}if ("age". Equals (name)) {person.setage (New short (Parser.nexttext ()));}} Break;case xmlpullparser.end_tag://End Element if ("person". Equals (Parser.getname ())) {persOns.add (person);p Erson = null;} break;} EventType = Parser.next ();} return persons;}}
In terms of memory footprint and execution efficiency, the Sax and pull methods should be considered as a priority to parse XML files.
Pull parsing XML for Android network programming