Parsing XML under Android network

Source: Internet
Author: User

XML (extensible Markup Language) Extensible Markup Language, which, like HTML, is SGML (Standard Universal Markup Language), which can be used to tag data, define data types, and is a source language that allows users to define their own markup language. It is ideal for world Wide Web transport, providing a unified approach to describing and exchanging structured data that is independent of the application or vendor. There are three ways to parse XML under Android, which are sax, DOM, pull, and they have their own characteristics, which are often used in network programming and which parsing method is chosen according to the actual situation.

1. Memory consumption

Because Android phone performance relative to the PC is still quite limited, the memory consumption of the program directly affects the speed of parsing XML, in the case of memory consumption, SAX, pull more than Dom occupy less

2. Programming method

Sax uses event-driven, each parsing a class of XML to write a suitable XML processing class, Dom is a specification, many languages can be used, easy to use, pull is the android comes with the parsing XML, using fewer parsers.

Sax is similar to pull, which works with large documents and requires only parts of the document, while the DOM is for small documents, random access, and changes to the document.

Let's see how it's used in the code.

Program directory Structure


XML file that needs parsing file.xml

<?xml version= "1.0" encoding= "Utf-8"?><persons> <person id=    "Ten" >        <name> Zhang San </ name>        <age>25</age>        <sex> men </sex>    </person>        <person id= "11" >        <name> John Doe </name>        <age>23</age>        <sex> women </sex>    </ person>    <person id= ">        <name> Harry </name>        <age>24</age>        <sex> women </sex>    </person>        <person id= >        <name> Zhao Liu </name>        <age>21</age>        <sex> men </sex>    </person>    </persons>
Parsing objects

Package Com.dzt.xml_parser.domain;public class Person {private int id;private String name;private short Age;private Strin G Sex;public Person () {}public person (int ID, string name, short age, string sex) {this.id = Id;this.name = Name;this.age = Age;this.sex = sex;} 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 short getage () {return age;} public void Setage {this.age = age;} Public String Getsex () {return sex;} public void Setsex (String sex) {this.sex = sex;} @Overridepublic String toString () {return "person [id=" + ID + ", name=" + name + ", age=" + age+ ", sex=" + Sex + "]";}

First, parsing XML using sax

Package Com.dzt.xml_parser;import Java.util.arraylist;import Java.util.list;import org.xml.sax.attributes;import Org.xml.sax.saxexception;import Org.xml.sax.helpers.defaulthandler;import Com.dzt.xml_ Parser.constant.globalconstants;import com.dzt.xml_parser.domain.person;/** * SAX parsing class, modified according to the actual situation * * @author Administrator * @date 2014.05.29 */public class Saxhandler extends DefaultHandler {private list<person> Persons;pri Vate String Pretag; Record the previous label private person Person;public list<person> Getperson () {return persons;} @Overridepublic void characters (char[] ch, int start, int length) throws Saxexception {//TODO auto-generated method Stubst Ring data = new String (CH, start, length). Trim (); Remove the space if (! "". Equals (data) {globalconstants.printlog_d ("[Saxhandler]->characters data =" + data);} if ("Name". Equals (Pretag)) {person.setname (data);} else if ("Age". Equals (Pretag)) {person.setage (new short (data));} else if ("Sex". Equals (Pretag)) {person.setsex (data);}} @Overridepublic void Enddocument () throws Saxexception {//TODO auto-generated method Stubglobalconstants.printlog_d ("[saxhandler]-> Enddocument ");} @Overridepublic void EndElement (String uri, String localname, String qName) throws Saxexception {//TODO auto-generated met Hod stubglobalconstants.printlog_d ("[saxhandler]->endelement");//To the end of a node if ("Person". Equals (LocalName)) { Persons.add (person);p Erson = null;} Pretag = null;} /** * Parsing the beginning of an XML document, doing initialization work here */@Overridepublic void Startdocument () throws Saxexception {//TODO auto-generated method Stu Bglobalconstants.printlog_d ("[saxhandler]->startdocument");p ersons = new arraylist<person> ();} @Overridepublic void Startelement (String uri, String localname, String Qname,attributes Attributes) throws Saxexception { TODO auto-generated Method stubif ("Person". Equals (LocalName)) {person = new person ();p Erson.setid (integer.valueof ( Attributes.getvalue (0)));} Pretag = LocalName; Globalconstants.printlog_d ("[Saxhandler]->startelement--end localname =" + LOcalname + "QName =" + QName);}} 
It is triggered by an event, a node to parse

Unit testing of code, if not clear how to add unit tests can be consulted: http://blog.csdn.net/deng0zhaotai/article/details/11482847

public void Testsaxgetpersons () throws Exception {InputStream is = GetContext (). Getresources (). Getassets (). Open (" File.xml "); Saxhandler handler = new Saxhandler (); SAXParserFactory SPF = saxparserfactory.newinstance (); SAXParser saxparser = Spf.newsaxparser (); Saxparser.parse (is, handler); list<person> list = Handler.getperson (); Is.close (); for (person person:list) {globalconstants.printlog_d ("[ Saxtest]->testsaxgetpersons "+ person.tostring ());}}

Test results


II. parsing XML using pull

Package Com.dzt.xml_parser;import Java.io.inputstream;import Java.util.arraylist;import java.util.List;import Org.xmlpull.v1.xmlpullparser;import Android.util.xml;import Com.dzt.xml_parser.domain.person;public Class Pullhandler {public static list<person> getpersons (InputStream is) throws Exception {list<person> List = null ; person person = null; Xmlpullparser parser = Xml.newpullparser ();p arser.setinput (IS, "UTF-8"); Set character encoding int event = Parser.geteventtype (); The first event triggered while (event! xmlpullparser.end_document) {switch (event) {case xmlpullparser.start_document://start parsing list = n EW arraylist<person> (); Break;case Xmlpullparser.start_tag://Start parsing element if ("person". Equals (Parser.getname ())) { int id = integer.valueof (parser.getattributevalue (0));p Erson = new Person ();p Erson.setid (ID);} if (person! = null) {if ("name". Equals (Parser.getname ()))} {Person.setname (Parser.nexttext ());} else if ("Age". Equals ( Parser.getname ())) {Person.setage (New short (Parser.nexttext ()));} else if ("sEx ". Equals (Parser.getname ())) {Person.setsex (Parser.nexttext ());}} Break;case Xmlpullparser.end_tag://End element if (' person '. Equals (Parser.getname ())) {List.add (person);p Erson = null;} Break;default:break;} event = Parser.next ();} return list;}}
The pull parser runs like the SAX parser, is event driven, has a start, end event, and Parser.next () can go to the next event

Test code

public void Testpullgetpersons () throws Exception {InputStream is = GetContext (). Getresources (). Getassets (). Open (" File.xml "); list<person> list = Pullhandler.getpersons (IS), for (person person:list) {globalconstants.printlog_d ("[SAXTest] ->testpullgetpersons "+ person.tostring ());}}

Test results


Third, parsing XML using the DOM

Package Com.dzt.xml_parser;import Java.io.inputstream;import Java.util.arraylist;import java.util.List;import Javax.xml.parsers.documentbuilder;import Javax.xml.parsers.documentbuilderfactory;import org.w3c.dom.Document; Import Org.w3c.dom.element;import org.w3c.dom.node;import Org.w3c.dom.nodelist;import Com.dzt.xml_ Parser.domain.person;public class Domhandler {public static list<person> getpersons (InputStream) throws Exception {list<person> List = new arraylist<person> ();D ocumentbuilderfactory factory = Documentbuilderfactory.newinstance ();D Ocumentbuilder builder = factory.newdocumentbuilder ();D ocument Document = Builder.parse (IS); Element root = Document.getdocumentelement ();  NodeList NodeList = root.getelementsbytagname ("person"), for (int i = 0; i < nodelist.getlength (); i++) {element element = (Element) nodelist.item (i); int id = integer.valueof (element.getattribute ("id")); person person = new person ();p Erson.setid (ID); NodeList childlist = Element.getchildnodes ();//How many elements each node has, traversing for (int j = 0; J < Childlist.getlength (), j + +) {if (Childlist.item (j). Getnodetype () = = Node.element_ NODE) {if ("name". Equals (Childlist.item (j). Getnodename ())) {String name = Childlist.item (j). Getfirstchild (). Getnodevalue ();p erson.setname (name);} else if ("Age". Equals (Childlist.item (j). Getnodename ())) {String age = Childlist.item (j). Getfirstchild (). Getnodevalue ();p erson.setage (new short);} else if ("Sex". Equals (Childlist.item (j). Getnodename ())) {String sex = Childlist.item (j). Getfirstchild (). Getnodevalue ();p erson.setsex (Sex);}}} List.add (person);} Is.close (); return list;}}

DOM is an object model for XML documents that directly accesses parts of an XML document, and the DOM is modeled as a tree


Test code

public void Testdomgetpersons () throws Exception {InputStream is = GetContext (). Getresources (). Getassets (). Open (" File.xml "); list<person> list = Domhandler.getpersons (IS), for (person person:list) {globalconstants.printlog_d ("[SAXTest]- >testdomgetpersons "+ person.tostring ());}}
Test results



Full demo Download: http://download.csdn.net/detail/deng0zhaotai/7422321


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.