Parsing XML with pull in Android

Source: Internet
Author: User
Tags xml parser

Parsing XML is dom,sax,pull, so why use pull parsing in Android? First of all, the advantages of pull parsing, and then again the other two analytic methods of the shortcomings, the answer is clearly visible.

DOM is not suitable for large, low-memory scenarios. The DOM is a collection of tree-based nodes or pieces of information that allow developers to traverse the XML tree using the DOM API and retrieve the data they need. Parsing the structure usually requires loading the entire document and constructing the tree structure before the node information can be retrieved and updated. Because the DOM is stored in memory in a tree structure, retrieval and update efficiency is higher. But for extremely large documents, parsing and loading the entire document can be resource-intensive.

SAX parser operation is too cumbersome, sax (simple API for XML) parser is an event-based parser, its core is the event processing mode, mainly around the event source and the event handler to work. When an event source generates an event, the event handler is called to handle the corresponding processing method, and an event can be processed. When the event source invokes a particular method in the event handler, it is also passed to the event handler for the status information of the corresponding event, so that the event handler can determine its behavior based on the event information provided. The advantage of the SAX parser is that the parsing is fast and consumes less memory. More suitable for use in Android mobile devices.

Pull parsing Advantages: ① lightweight and flexible, fast speed. ② occupies memory (great advantage) ③ easy to use. The pull parser operates in a similar manner to sax, and is an event-based pattern. The difference is that during pull parsing, we need to get the generated events and do the corresponding operations, instead of executing our code in a way that the processor triggers an event like sax. The pull parser is compact, fast, and easy to use, and is ideal for Android mobile devices, and the pull parser is used to parse various XML inside the Android system.

Then I'll introduce the pull parser:

first, in the project's assets directory, place an XML document Person.xml that you want to parse, with the following:

<?xml version= "1.0" encoding= "UTF-8"?>
<persons>
<person id= "1" >
<name>John</name>
<age>23</age>
</person>
<person id= "2" >
<name>David</name>
<age>233</age>
</person>
</persons>

Then modeled on the person object in XML, Person.java is as follows:

Package com.example.xml_paser;
public class Person {
private int id;
private String name;
private int age;
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 int getage () {
return age;
}
public void Setage (int.) {
This.age = age;
}
}

Then using Pullparser parsing, the code is as follows:

Package com.example.xml_paser;

Import Java.io.InputStream;
Import java.util.ArrayList;
Import java.util.List;

Import Org.xmlpull.v1.XmlPullParser;

Import Android.content.Context;
Import Android.util.Log;
Import android.util.Xml;

public class Xml_paser {
Static final String TAG = "Xmlpaser";
private static final String ns = null;
Private context context;

Public Xml_paser (Context applicationcontext) {
TODO auto-generated Constructor stub
This.context = ApplicationContext;
}

Public list<person> Parse (String xmlpath) {
list<person> psonlist = new arraylist<person> ();//Create a list of person objects
person person = null;
InputStream stream = null;
Get XML Parser
Xmlpullparser xmlparse = Xml.newpullparser ();//Create Xmlpullparser instance
try {
Get file stream and set encoding
stream = This.context.getResources (). Getassets (). open (Xmlpath);//Initialize input stream
Xmlparse.setinput (Stream, "utf-8");//set the input stream and indicate the encoding method
Get Event Type
int evntype = Xmlparse.geteventtype ();
Continue to end document
while (evntype! = xmlpullparser.end_document) {
Switch (evntype) {
Case Xmlpullparser.start_tag:
String tag = Xmlparse.getname ();//Get Parse tag name
if (Tag.equalsignorecase ("person")) {//tag is the case of person
person = new person ();//Create Person Object
Person.setid (Integer.parseint (xmlparse
. Getattributevalue (NS, "id")));//Get the id attribute in the input stream and assign it to the ID of the new Person object
} else if (person! = null) {
Parse after tag
if (tag.equalsignorecase ("name")) {
Person.setname (Xmlparse.nexttext ());//Get the name attribute in the input stream and assign it to the name of the new Person object
} else if (Tag.equalsignorecase ("Age")) {
Person.setid (Integer.parseint (Xmlparse.nexttext ()));
}
}
Break
Case Xmlpullparser.end_tag:
if (Xmlparse.getname (). Equalsignorecase ("person")
&& person! = null) {
Psonlist.add (person);//Add Person object to Personlist
person = null;
}
Break
Default
Break
}
Evntype = Xmlparse.next ();
}
} catch (Exception e) {
LOG.D (TAG, e.tostring ());
}
return psonlist;
}
}

Finally, we need to call the pull resolver, which is done in mainactivity:

Package com.example.xml_paser;
Import java.util.List;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.Button;
public class Mainactivity extends Activity {
Private Button Btn_paserbutton;
Private String urlstring= "person.xml";
Private Xml_paser Xml_paser;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
btn_paserbutton= (Button) Findviewbyid (R.id.button1);
Xml_paser=new Xml_paser (Getapplicationcontext ());
Btn_paserbutton.setonclicklistener (New View.onclicklistener ()
{
@Override
public void OnClick (View arg0) {
TODO auto-generated Method Stub
list<person> list_per = Xml_paser.parse (urlstring);
LOG.V ("BBB", list_per.size () + "");
for (int i = 0; i < list_per.size (); i++)
{
LOG.V ("AAA", List_per.get (i));
LOG.V ("AAA", List_per.get (i). GetName (). toString () + "");
}
}
});
}
}

The result of the operation shows the person's name with the following results:

Parsing XML with pull in Android

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.