Android uses pull to parse XML

Source: Internet
Author: User
Tags gettext

Overview:

The pull parser is compact, fast, and easy to use, ideal for Android mobile devices, and the pull parser is used internally by Android to parse various types of XML, and Android recommends that developers use pull parsing technology. Pull parsing technology is an open source technology developed by third parties, and it can also be applied to javase development.

How Pull works:

The XML pull provides the start element and the end element. When an element starts, you can call parser. Nexttext extracts all character data from the XML document. The Enddocument event is automatically generated when parsing to the end of a document.

Common XML pull interfaces and classes:

Xmlpullparser: The parser is an interface for parsing functionality defined in ORG.XMLPULL.V1.

XmlSerializer: It is an interface that defines a sequence of XML information sets.

Xmlpullparserfactory: This class is used to create an XML pull parser in the Xmpull V1 API.

Xmlpullparserexception: Throws a single XML pull parser related error.

The pull parser operates in a similar manner to sax, and is an event-based pattern.

The difference is that the numbers are returned during pull parsing, and we need to get the generated events ourselves and do the corresponding operations, instead of executing our code in a way that the processor triggers an event as SAX does:

Read the declaration to XML return start_document; end return end_document; start tag return start_tag;

The end tag returns End_tag;

Comparison and summary of several analytic techniques:
For Android mobile devices, because the resources of the device is more valuable, memory is limited, so we need to choose the appropriate technology to parse the XML, which helps to improve the speed of access.

When the DOM processes an XML file, it parses the XML file into a tree structure and puts it into memory for processing. When the XML file is small, we can choose the DOM because it is simple and intuitive.

Sax is a pattern of parsing an XML file with events, which transforms an XML file into a series of events that are determined by different event handlers. When the XML file is large, it is reasonable to choose Sax technology. Although the amount of code is somewhat large, it does not need to load all the XML files into memory. This is more efficient for limited Android memory, and Android offers a traditional sax usage and a handy sax wrapper. Use Android. Util XML classes, as you can see from the example, are simpler than using sax.

XML pull parsing does not listen to the end of the element as sax parsing does, but rather completes most of the processing at the beginning. This facilitates early reading of XML files, which can greatly reduce parsing time, which is especially important for mobile devices with a more connected speed. The XML pull parser is a more efficient method for XML documents that are large but require only a portion of the document.

Development examples:

The books.xml file is defined in asset, and as long as it is a well-formed XML document, the specific content is defined as needed.

Read xml: Parse and display from a well-defined books.xml file;

Write xml: The parsed content is then written to the local, and this is also saved as a file named Books.xml.

For example: Books.xml defines the following form:

<?xml version= "1.0" encoding= "Utf-8"?><books><book><id>1001</id><name> Thinking in Java</name><price>80.00</price></book><book><id>1002</id> <name>core java</name><price>90.00</price></book><book><id>1003</ Id><name>hello, andriod</name><price>100.00</price></book></books>  

Full code:

Pullparseractivity:

Package Com.xsjayz.xml;import Java.io.fileoutputstream;import Java.io.inputstream;import java.util.List;import Android.app.activity;import Android.content.context;import Android.os.bundle;import Android.util.Log;import Android.view.view;import android.widget.button;import android.widget.textview;/** * Pull parser, Here is a simple definition of a textview display parsing result, two button operations.  * * @since 2012-08-23 */public class Pullparseractivity extends Activity {private static final String TAG = "XML";p rivate TextView TextView = null;private button readbtn = null;private button writebtn = null;private bookparser parser;private L Ist<book> bookslist; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.main); TextView = (TextView) Findviewbyid (r.id.txt); readbtn = (Button) Findviewbyid (r.id.read_btn); writebtn = (Button) Findviewbyid (R.ID.WRITE_BTN); Readbtn.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {try {InputStream is = gEtassets (). Open ("books.xml");p Arser = new Pullbookparser (), bookslist = Parser.parse (IS), for (book book:bookslist) {Log . I (TAG, book.tostring ());} for (book book:bookslist) {Textview.settext (Textview.gettext () + book.tostring ());}} catch (Exception e) {log.e (TAG, E.getmessage ());}}); Writebtn.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {try {String xmlstring = Parser.serialize (bookslist); Serialized FileOutputStream fos = openfileoutput ("books.xml", context.mode_private); Fos.write (Xmlstring.getbytes ("UTF-8" ));} catch (Exception e) {log.e (TAG, E.getmessage ());}});}}

Pullbookparser:

Package Com.xsjayz.xml;import Java.io.inputstream;import Java.io.stringwriter;import java.util.arraylist;import Java.util.list;import Org.xmlpull.v1.xmlpullparser;import Org.xmlpull.v1.xmlserializer;import android.util.Xml;/* * Pull parser, implements the Bookparser interface */public class Pullbookparser implements Bookparser {/** * @param is * @return bookslist */@Ov Erridepublic list<book> Parse (InputStream is) throws Exception {list<book> bookslist = null; Book book = null;//creates an Xmlpullparser instance from android.util.Xml xmlpullparser parser = Xml.newpullparser ();//Set input stream and indicate the encoding method Parser.setinput (IS, "UTF-8");//generates the first event int eventtype = Parser.geteventtype (); while (eventtype! = xmlpullparser.end_document) {switch (EventType) {//Determines whether the current event is a document start event case XmlPullParser.START_DOCUMENT:booksList = new Arraylist<book> (); Initializes the books collection break;//determines whether the current event is a LABEL element start event Case XmlPullParser.START_TAG:if (Parser.getname (). Equals ("book")) {// Determines whether the start tag element is BookBook = new book ();} else if (Parser.getname (). Equals ("id")) {EventType = Parser.next ();//Get the property value of the book tag and set the book's Idbook.setid (Integer.parseint (Parser.gettext ()));} else if (Parser.getname () equals ("name")) {//Determine if the start tag element is Bookeventtype = Parser.next (); Book.setname (Parser.gettext () );} else if (Parser.getname () Equals ("price")) {//Determines whether the start tag element is Priceeventtype = Parser.next (); Book.setprice ( Float.parsefloat (Parser.gettext ()));} break;//determines whether the current event is a LABEL element end Event Case XmlPullParser.END_TAG:if (Parser.getname (). Equals ("book")) {// Determines whether the end tag element is Bookbookslist.add (book); Add book to books collection book = null;} break;} Enter the next element and trigger the corresponding event EventType = Parser.next ();} return bookslist;}  /** * @param books * @return writer.tostring () */@Overridepublic String serialize (List<book> books) throws Exception {//Create a XmlSerializer instance from android.util.Xml xmlserializer serializer = Xml.newserializer (); StringWriter writer = new StringWriter ();//Set the output direction to Writerserializer.setoutput (writer); Serializer.startdocument (" UTF-8 ", true); Serializer.starttag (" "," books "); for (book book:books) {Serializer.starttag (""," "book"); Serializer.attribute ("", "id", Book.getid () + ""), Serializer.starttag ("", "name"); Serializer.text ( Book.getname ()); Serializer.endtag ("", "Name"), Serializer.starttag ("", "price"), Serializer.text (Book.getprice () + " Serializer.endtag (",", "price"), Serializer.endtag ("", "book"); Serializer.endtag ("", "books"); Serializer.enddocument (); return writer.tostring ();}}

Bookparser:

Package Com.xsjayz.xml;import Java.io.inputstream;import Java.util.list;public interface Bookparser {/** * Parse input stream Get a collection of book objects *  * @param is * @throws Exception */public list<book> Parse (InputStream is) throws exception;/** * sequence The collection of book objects gets the string in XML form *  * @param books * @throws Exception */public string serialize (List<book> books) throws Ex Ception;}

Book:

Package com.xsjayz.xml;/** * Book's model class, which defines all the states, accessors, and modifiers of book, overrides the ToString method */public class Book {private int id;private String name;private float price;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public float GetPrice () {return price;} public void Setprice (float price) {this.price = Price;} @Overridepublic String toString () {return ' ID: ' + ID + ' \nname: ' + name + ' \nprice: ' + price + ' \ n ';}}

Android uses pull to parse XML

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.