Android Development Series (eight): parsing and generating XML content with the pull parser

Source: Internet
Author: User

Because sometimes the application data is stored in XML file format, so we need to know how to read the data from the XML file.

In Android, XML files can be parsed by sax, DOM, and pull.

In this blog post, we mainly describe parsing and generating XML content using the pull parser.

Description: The pull parser has been integrated on Android so there is no need to add any jar files. The various XML files used in Android itself are also parsed using the pull parser.


First, using the pull parser to parse the XML file content

First, we need to first build an Android project with the name: XML. The default build Mainactivity.java, under the Cn.itcast.xml package, the contents of this Java file are automatically generated.


Then, we create an XML file in the SRC directory: person.xml:

<?xml version= "1.0" encoding= "UTF-8"?> <!--This file header is the Start document event--><persons><person id= "1" ><name>zhangsan</name><age>30</age></person><person id= "2" ><name> Lisi</name><age>25</age></person></persons>
You can see that this XML file has two person information stored.


Next, we need to create a JavaBean to reflect the XML file, Person.java (note that the attributes in this bean are corresponding to the XML, otherwise it will not parse correctly):

Package Cn.itcast.domain;public class Person {private integer id;private String name;private an integer age; @Overridepublic String toString () {return "person [id=" + ID + ", name=" + name + ", age=" + Age + "]";} Public Integer GetId () {return ID;} public void SetId (Integer id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public Integer Getage () {return age;} public void Setage (Integer age) {this.age = age;}}
In this Java file we define three properties: ID, name, age, and generate a ToString () method


After the entity class is built, we need to write the class of the business layer, Personservice.java:

Package Cn.itcast.service;import Java.io.inputstream;import Java.util.arraylist;import java.util.List;import Cn.itcast.domain.*;import Org.xmlpull.v1.xmlpullparser;import Org.xmlpull.v1.xmlpullparserfactory;import Android.util.xml;public class Personservice {public static list<person> getpersons (InputStream Xml) throws exception{list<person> persons = NULL; Person person = null;//Gets the parser/* This method is the same as the bottom function, you can get the parser: xmlpullparser Pullparser = Xmlpullparserfactory.newinstance (). Newpullparser (); */xmlpullparser pullparser = Xml.newpullparser ();p ullparser.setinput (Xml, "UTF-8");// Set the XML data to parse for the pull parser int event = Pullparser.geteventtype (); Produces the first event: Start Documentwhile (Event! = xmlpullparser.end_document) {switch (event) {//event is judged case Xmlpullparser.start _document:persons = new arraylist<person> (); Break;case XmlPullParser.START_TAG:if ("person". Equals ( Pullparser.getname ())) {int id = new Integer (pullparser.getattributevalue (0));p Erson = new Person ();p Erson.setid (ID);} if ("Name". Equals (PulLparser.getname ())) {String name = Pullparser.nexttext ();p erson.setname (name);} if ("Age". Equals (Pullparser.getname ())) {int. = new Integer (Pullparser.nexttext ());p erson.setage (age);} Break;case XmlPullParser.END_TAG:if ("person". Equals (Pullparser.getname ())) {Persons.add (person);p Erson = null;} break;} event = Pullparser.next ();} return persons;}}
This code is more troublesome, and we'll look at the following specific analysis:

Xmlpullparser pullparser = Xml.newpullparser (); This code is to get a pull parser, in addition:xmlpullparser pullparser = Xmlpullparserfactory.newinstance (). Newpullparser (); You can also get the pull parser.

pullparser.setinput (XML, "UTF-8"); Used to set the encoding format of the XML file to parse, this is "UTF-8"

Because the pull parser is a process of traversing a document, it starts from <?xml version= "1.0" encoding= "UTF-8"?> this start document event until </persons> ends.

int event = Pullparser.geteventtype (); At this point, the document is initialized, and here you get the document's start file, which is the Start_document event.

Then, it is a while loop, and the restriction is the event! = Xmlpullparser.end_document, that is, the currently traversed node does not reach the end, it executes the while loop.

Inside the while loop is a switch () control statement that controls which node is currently selected and has three case:

Case xmlpullparser.start_document: satisfies the Start_document event (that is, the beginning of the XML file)

Case Xmlpullparser.start_tag: satisfies the Start_tag event (that is, the beginning of the XML element node: for example, <person> in this article)

Case Xmlpullparser.end_tag:: satisfies the End_tag event (that is, the end of the XML element node: for example, </person> in this article)

In the second case, we made three judgments:

If ("Person". Equals (Pullparser.getname ())): If the person element node is reached, the ID is assigned to the person

If ("name". Equals (Pullparser.getname ())): If the name element node is reached, the name is assigned to the person

If ("Age". Equals (Pullparser.getname ())): If the age element node is reached, the age is assigned to the person


Note that at the end of each switch () control statement, there is an event = Pullparser.next (), which means to point the pull parser pointer to the next node.



Above, we are done with the pull parser, and then we write a test class:

Note that configuring Androidmanfiest.xml first introduces the syntax of the test, which is not much to say here.

Write the Personservicetest.java, and put it in the Cn.itcast.test file directory:

Package Cn.itcast.test;import Java.io.inputstream;import Java.util.list;import cn.itcast.domain.person;import Cn.itcast.service.personservice;import Android.test.androidtestcase;import Android.util.log;public Class Personservicetest  extends androidtestcase{private static final String TAG = "Personservicetest";p ublic void Testpersons () throws exception{//through the getClassLoader () method to get the input stream of the Person.xml file in the src directory inputstream XML = This.getclass (). getClassLoader (). getResourceAsStream ("person.xml"); list<person> persons = Personservice.getpersons (XML); for (person person:persons) {log.i (TAG, person.tostring ()) ;}}}
We then add a filter to the Logcat page:

You can print out the persons on the Logcat page.


Second, using the Pull parser to generate XML content






Android Development Series (eight): parsing and generating XML content with the pull parser

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.