Android Tour 14 XML file parsing in Android

Source: Internet
Author: User

As we do about the Android project, it will certainly involve parsing the XML file, and let us introduce the parsing of the XML file, including DOM, SAX, pull, and the dom4j and jdom we used before:

XML file to parse: person.xml

<?xml version= "1.0" encoding= "UTF-8"? ><persons><person id= "001" ><name>zhangsan</name ><age>25</age></person><person id= "002" ><name>lisi</name><age>23 </age></person></persons>

To create a person entity class:

Package Cn.itcast.domain;public class Person {private Integer id;private String name;private short age;public person () {}p Ublic person (Integer ID, String name, short age) {this.id = Id;this.name = Name;this.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 short getage () {return age;} public void Setage {this.age = age;} @Overridepublic String toString () {return "person [age=" + Age + ", id=" + ID + ", name=" + name + "]";}}


1, Dom parsing xml:dom parsing is to load the XML file, assemble it into a DOM tree, and parse the XML file through the relationships between the nodes and the nodes.

public static list<person> getpersons (InputStream instream) throws throwable{list<person> persons = new Arraylist<person> ();//Create parser factory Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();// Create parser Documentbuilder builder = Factory.newdocumentbuilder ();//Create a document Tree model, all of which are contained in a certain order within the Document object,//arranged into a tree structure, All subsequent operations on the XML document are not related to the parser. Document documnet = Builder.parse (instream);//get root element elements root = Documnet.getdocumentelement () ;//Get the list of person nodes under the root element nodelist Personnodes = root.getelementsbytagname ("person"), for (int i=0; i < Personnodes.getlength (); i++) {Person person = new person ();//gets element elements in node Personelement = (Element) personnodes.item (i);// Gets the id attribute person.setid (new Integer (Personelement.getattribute ("id")) in person, and/or gets the child node under the person node nodelist personchilds = Personelement.getchildnodes (); for (int y=0; y < Personchilds.getlength (); y++) {if (Personchilds.item (y)). Getnodetype () ==node.element_node) {//To determine if the current node is an element type node-childelement = (Element) personchilds.item (y);("Name". Equals (Childelement.getnodename ())) {//Get the value of the corresponding element Person.setname (Childelement.getfirstchild (). Getnodevalue ());} else if ("Age". Equals (Childelement.getnodename ())) {Person.setage (New short (Childelement.getfirstchild ()). Getnodevalue ()));}}} Persons.add (person);} return persons;}

2, Sax parsing xml: Sequential read XML file, do not need to load the entire file at once, because of the limited memory resources of the mobile device, Sax sequential reading method is more suitable for mobile development

Public list<person> getpersons (InputStream instream) throws throwable{//Create Saxparserfactorysaxparserfactory    Factory = Saxparserfactory.newinstance (); Create SAX parser SAXParser parser = Factory.newsaxparser ();//create XML parsing processor Personparser Personparser = new Personparser ();// The XML parsing processor is assigned to the parser, parsing the document, sending each event to the processor Parser.parse (instream, Personparser); Instream.close (); return Personparser.getpersons ();} Define resolution processor private Final class Personparser extends defaulthandler{private list<person> persons = null;// Place the parsed data in the list collection private String tag = null;//defines the label name of a global variable private person person = Null;public list<person> Getpersons () {return persons;} Parsing document@overridepublic void Startdocument () throws Saxexception {//parse <persons> section persons = new arraylist< Person> ();} @Overridepublic void Enddocument () throws Saxexception {System.out.println ("End parse xml"); /** * Parse Element * NamespaceURI namespace * localname without prefix part <person id= "001" >--->person * qName with prefix part <abc:person id= "001" >---->abc:worker * Attributes property Collection <abc:person id= "001" >---->id= "001" .... */@Overridepublic void Startelement (String uri, String localname, String qName, Attributes Attributes) throws Saxexception {//parse <person id= "0 "> section if (" Person ". Equals (LocalName)) {person = new person ();p Erson.setid (New Integer (Attributes.getvalue (0))} tag = LocalName;} @Overridepublic void characters (char[] ch, int start, int length) throws Saxexception {//parse the text in it <name>zhangsan< /name>-->zhangsanif (tag!=null) {String data = new String (ch, start, length);//Gets the data for the text node if ("Name". Equals (tag)) { Person.setname (data);} else if (' Age '. Equals (Tag)} {person.setage (new short (Data)}}} Resolves the end element @overridepublic void EndElement (String uri, String localname, String qName) throws Saxexception {if ("person"). Equals (LocalName)) {Persons.add (person);p Erson = null;} tag = null;}}

3, pull parsing xml:pull parsing and sax parsing are very similar, are lightweight parsing, in the Android kernel has embedded pull, so we do not need to add third-party jar to support pull

/** * Parse XML document using Pull * @param instream * @return * @throws throwable */public static list<person> getpersons (inputstr Eam instream) throws throwable{list<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 a document End Event switch (eventtype) {case Xmlpullparser.start_ DOCUMENT://determines whether the current event is a document start event persons = new arraylist<person> ();//Initialize person collection Break;case Xmlpullparser.start_tag ://Determines whether the current event is a LABEL element start Event String name = Parser.getname ();//Gets the name of the element that the parser is currently pointing to if ("person". Equals (name)} {person = new person () ;//Get the property value of the corresponding tag Person.setid (new Integer (Parser.getattributevalue (0)));} if (person!=null) {if ("name". Equals (name)) {//Gets the value of the next text node that the parser currently points to the element Person.setname (Parser.nexttext ());} if ("Age". Equals (name)) {person.setage (New short (Parser.nexttext ()));}} Break;case xmlpullparser.end_tag://Determines whether the current event is a tag element end event if ("Person". Equals (Parser.getname ())) {PERSONS.ADD (person);p Erson = null;} break;} Enter the next element and trigger the corresponding event EventType = Parser.next ();} return persons;}
Create an XML document with the Pull parser:

/** * Create an XML document using the Pull parser * @param persons * @param writer * @throws throwable */public static void Save (list<person> Persons, writer writer) throws Throwable{xmlserializer serializer = Xml.newserializer (); Serializer.setoutput (writer); Serializer.startdocument ("UTF-8", true); Serializer.starttag (null, "persons"); for (person Person:persons) { Serializer.starttag (null, "person"); Serializer.attribute (NULL, "id", Person.getid (). toString ()); Serializer.starttag (NULL, "name"); Serializer.text (Person.getname ()); Serializer.endtag (null, "name"); Serializer.starttag (NULL, "age"); Serializer.text (Person.getage (). toString ()); Serializer.endtag (null, ' age '); Serializer.endtag (null, "person");} Serializer.endtag (NULL, "persons"); Serializer.enddocument (); Writer.flush (); Writer.close ();}
Test each method with JUnit on your Android project:

Note that when using JUnit, you need to include the following in the Androidmainifest.xml:

<uses-library android:name= "Android.test.runner"/><instrumentation android:name= " Android.test.InstrumentationTestRunner "  android:targetpackage=" com.xin.activity "android:label=" Tests for My App "/>
To write our Java Test class:

public class Personservicetest extends Androidtestcase {private static final String TAG = "Personservicetest";p ublic void Testsaxgetpersons () throws Throwable{saxpersonservice service = new Saxpersonservice (); InputStream instream = GetClass ( ). getClassLoader (). getResourceAsStream ("person.xml");    list<person> persons = Service.getpersons (instream); for (person person:persons) {log.i (TAG, person.tostring ()); }}public void Testdomgetpersons () throws Throwable{inputstream instream = GetClass (). getClassLoader (). getResourceAsStream ("person.xml"); list<person> persons = Dompersonservice.getpersons (instream); for (person person:persons) {log.i (TAG, Person.tostring ());}} public void Testpullgetpersons () throws Throwable{inputstream instream = GetClass (). getClassLoader (). getResourceAsStream ("person.xml"); list<person> persons = Pullpersonservice.getpersons (instream); for (person person:persons) {log.i (TAG, Person.tostring ());}}}

Run the output to get the results we want!

Comparison of several methods:

SAX: Read on one line, high efficiency, read to the corresponding required data no longer down operation, complex operation, suitable for mobile devices
Dom: Simple operation, the start of loading a DOM tree, when the XML file relative to the big time impact efficiency, slow

* Pull parsing does not have the same place as Sax parsing
* (1) Pull reads the XML file and triggers the corresponding event call method to return a number
* (2) pull can be in the program to control where you want to resolve to stop parsing

In fact, pull parsing XML is not only suitable for Android, but we can also use the Pull parser to parse XML files in our javase, but we need to import the appropriate jar packages:

Kxml2-2.3.0.jar,:http://kxml.sourceforge.net/

Xmlpull_1_1_3_4c.jar :http://www.xmlpull.org/

We used dom4j and Jdom to parse the XML, which we can see in my blog, but I need to import the appropriate support jar package:

DOM4J parsing xml:http://blog.csdn.net/harderxin/article/details/7285770

Jdom parsing xml:http://blog.csdn.net/harderxin/article/details/7285754

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.