Several common methods of parsing XML Sax,dom,pull take Android as an example

Source: Internet
Author: User

Preparatory work
First is a person.xml file

<?xml version= "1.0" encoding= "UTF-8"? ><persons><person id= "><name>allen</name>" <age>36</age></person><person id= "><name>james</name><age>25</" Age></person></persons>

The corresponding JavaBean

public class Person {private Integer id;private String name;private short 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;}}


Place the Person.xml in the Android assert directory:


Android reads the XML file code in assets:

Assetmanager manager = Context.getassets (); InputStream is  = manager.open (filename);

Sax parsing: Principle:

SAXis a fast resolution and consumes less memory.XMLparser, which is ideal forAndroidand other mobile devices. SAXparsingXMLthe file is event-driven, that is, it does not need to parse the entire document, in the process of parsing the document in order of content ,SAXdetermines whether the currently read character is legalXMLa part of the syntax that triggers an event if it is met. The so-called events are actually some callbacks (Callback) methods, these methods(Events)defined inContentHandlerinterface. Here are someContentHandlerCommon methods of interface:

startdocument ()

When you encounter the beginning of a document, call this method, where you can do some preprocessing work.

enddocument ()

Corresponding to the above method, when the document is finished, call this approach, you can do some work in the aftermath.

startelement (String namespaceuri ,string localname ,string qname ,attributes atts )

namespaceuri localname qname atts sax startelement () Span style= "Color:black" > All of the information you know is the name and attributes of the tag, as for the nested structure of the tag, the name of the upper label, whether there are any other structure-related information, such as the sub-genus, and so on, all of which need your program to complete. This causes the sax dom

endElement (string uri, string localname, string name)

This method corresponds to the above approach, which is called when the end tag is encountered.

characters (char[] ch,int start, int length)

This method is used to process XML The contents of the file are read, the first parameter is the string content of the file, and the following two parameters are the starting position and length of the string to be read in the array, using the New String (ch,start,length) to get the content.

as Long as SAX provides implementation ContentHandler interface, then the class can get a notification event (which is actually SAX called the callback method in the Class). Because ContentHandler is an interface that may be inconvenient when used,SAX has also developed a Helper for it class:defaulthandler, which implements the contenthandler interface, but all of its method bodies are empty, When implemented, you only need to inherit the class, and then rewrite the appropriate method.

UseSAXparsingPerson.xml:
public static list<person> ReadXML (InputStream instream) {   try {saxparserfactory SPF = Saxparserfactory.newinstance (); SAXParser saxparser = Spf.newsaxparser (); Create parser//Set the correlation property of the parser, http://xml.org/sax/features/namespaces = True to open the namespace attribute  //saxparser.setproperty ("http/ Xml.org/sax/features/namespaces ", true); Xmlcontenthandler handler = new Xmlcontenthandler () Saxparser.parse (instream, handler); Instream.close (); return Handler.getpersons ();   } catch (Exception e) {e.printstacktrace ();   }  return null;}

Xmlcontenthandler The code implementation :

public class Xmlcontenthandler extends DefaultHandler {private list<person> persons = Null;private person Currentpe Rson;private String tagName = null;//element tag of the current parsing public list<person> getpersons () {return persons;} /* * Receive notification of the beginning of the document. */@Override public void Startdocument () throws saxexception {persons = new arraylist<person> ();} /* * Receive notification of character data. */@Override public void characters (char[] ch, int start, int length) throws Saxexception {if (tagname!=null) {String data = New String (CH, start, length), if (Tagname.equals ("name")) {this.currentPerson.setName (data);} else if (tagname.equals ("Age")) {This.currentPerson.setAge (Short.parseshort (data));}} /* * Receive notification of the start of the element. * Parameters are as follows: * NamespaceURI: namespace of Element * LocalName: Local name of element (without prefix) * QName: Qualified name of Element (prefixed) * Atts: Collection of attributes of element/@Override P ublic void Startelement (String NamespaceURI, String LocalName, String qName, Attributes atts) throws Saxexception {if (loca Lname.equals ("person")) {Currentperson = new person (); Currentperson.setid (Integer.parsEint (Atts.getvalue ("id")));} This.tagname = LocalName;} /* * Receive notification at the end of the document. * parameter meaning is as follows: * URI: Element namespace * LocalName: element's local name (without prefix) * Name: The qualified name of the element (prefixed) * */@Override public void EndElement (STR ing URI, string localname, String name) throws Saxexception {if (localname.equals ("person")) {Persons.add (Currentperson) ; currentperson = null;} This.tagname = null;}}

Dom parsing: Principle:

in addition to usingSAXcan parseXMLfile,You can also use the familiarDOMto parseXMLfile. DOMparsingXMLfile, you willXMLall the contents of the file are stored in memory in the document tree and then allow you to use theDOM APITraverseXMLtree and retrieve the required data. UseDOMOperationXMLcode appears to be more intuitive and is more coded thanSAXEasier to implement. However, becauseDOMneed to beXMLall the contents of the file are stored in memory in the document tree, so the memory consumption is large, especially for runningAndroidmobile devices, because the resources of the device are more valuable, it is recommended to useSAXto parseXMLdocument, of course, ifXMLthe content of the file is relatively small to useDOMis also feasible.

code example:

/** * Parsing XML files using DOM * */public class Domxmlreader {public static list<person> ReadXML (InputStream instream) {list< person> persons = new arraylist<person> ();D ocumentbuilderfactory factory = Documentbuilderfactory.newinstance (); try {Documentbuilder builder = Factory.newdocumentbuilder ();D ocument dom = Builder.parse (instream); Element root = Dom.getdocumentelement (); NodeList items = root.getelementsbytagname ("person");//Find all person nodes for (int i = 0; i < items.getlength (); i++) {person person = new ();//Gets the first man node Element Personnode = (Element) items.item (i);//Gets the id attribute value of the person node Person.setid (new Integer (Personnode.getattribute ("id")));//Gets all child nodes under the person node (white space nodes and name/age elements between labels) NodeList childsnodes =                        Personnode.getchildnodes (); for (int j = 0; J < Childsnodes.getlength (); j + +) {node node = (node) childsnodes.item (j);                              Determines whether the element type if (node.getnodetype () = = Node.element_node) {element childnode = (element) node; Determine if NAThe Me element if ("name". Equals (Childnode.getnodename ())) {//Gets the name element under the text node, and then gets the data from the text node per    Son.setname (Childnode.getfirstchild (). Getnodevalue ()); } else if ("Age". Equals (Childnode.getnodename ())) {Person.setage (New short (Childnode.getfirstchild (). Getnodevalue ()    )); }}} persons.add (person);} Instream.close ();} catch (Exception e) {e.printstacktrace ();} return persons;}

Pull parsing: Principle:

in addition to usingSAXorDOMparsingXMLoutside the file,You can also useAndroidbuilt -in PullParser ParsingXMLfile. PullThe parser is an open sourceJavaproject that can be used for bothAndroid, can also be used tojava EE. If used injava EEneed to put itsJarfile into the classpath becauseAndroidhas been integrated into the Pullparser, so there is no need to add anyJarfile. Androidthe system itself uses a variety ofXMLdocument, the interior is also used PullParsed by the parser. Pullthe way the parser runs andSAXParsersimilar. It provides similar events, such as: start element and end element event, usingParser.next()you can go to the next element and trigger the corresponding event. WithSAXthe difference is that Pullthe event generated by the parser is a number, not a method, so you can use aSwitchhandle the event of interest. When the element begins parsing, the callParser.nexttext()method to get the nextTextthe value of the type node.

code Example:

public class Pullxmlreader {public static list<person> ReadXML (InputStream instream) {xmlpullparser parser = Xml.ne Wpullparser (); try {parser.setinput (instream, "UTF-8"); int eventtype = Parser.geteventtype (); person Currentperson = null; list<person> persons = Null;while (EventType! = xmlpullparser.end_document) {switch (eventtype) {case xmlpullparser.start_document://Document Start event, data initialization can be processed persons = new arraylist<person> (); break;case xmlpullparser.start_tag://Start element Event String name = Parser.getname (); if (Name.equalsignorecase ("person")) {Currentperson = New person (); Currentperson.setid (New Integer (Parser.getattributevalue (NULL, "id"));} else if (Currentperson! = null) {if (Name.equalsignorecase ("name")) {Currentperson.setname (Parser.nexttext ());// If it is followed by a text node, it returns its value} else if (Name.equalsignorecase ("Age")) {Currentperson.setage (New short (Parser.nexttext ()));}} Break;case xmlpullparser.end_tag://End Element Event if (Parser.getname (). Equalsignorecase ("person") && Currentperson! = null) {Persons.add (Currentperson); Currentperson = null;} break;} EventType = Parser.next ();} Instream.close (); return persons;} catch (Exception e) {e.printstacktrace ();} return null;}}



Several common methods of parsing XML Sax,dom,pull take Android as an example

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.