"Android Advanced" XML file DOM, SAX, pull three parsing methods of the full solution

Source: Internet
Author: User

have been busy with the final exam review, but review quite boring, accidentally see XML parsing method, although previously done, but feel is not very familiar with, so take some time to three ways to review all over. In these three methods the DOM consumes memory most, because it is the entire file loaded and then sorted, pull and sax similar, only sax to use a parsing class, the main three methods of the class to complete the content parsing, and the Pull method is unique to Android, based on the obtained tags to judge and parse , which is the most commonly used method in Android.

Next to everyone review, because I think the code is easier to understand, the explanation is not much.

First we prepare the resource files we want to parse and the encapsulated JavaBean.

Person.xml

<?xml version= "1.0" encoding= "UTF-8"?>  <persons>    <person id= "1" >        <name>sax </name>        <age>12</age>    </person>    <person id= "2" >        <name> ganganrou</name>        <age>17</age>    </person>    <person id= "3" >        < name>nuanwozi</name>        <age>5</age>    </person></persons>

packaged JavaBean

public class Personbean {int id; String name; String 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 String Getage () {return age;} public void Setage (String age) {this.age = age;} @Overridepublic String toString () {return "Personbean [id=" + ID + ", name=" + name + ", age=" + Age + "]";}}

Next we parse the Person.xml file in Dom, SAX, pull, and encapsulate it in JavaBean:

First, DOM

public static list<personbean> Getpersonbeans () {list<personbean> List = new Arraylist<personbean> () ;D ocumentbuilderfactory builderfactory = documentbuilderfactory.newinstance (); try {Documentbuilder builder = Builderfactory.newdocumentbuilder ();D ocument Document = Builder.parse (DomPaserHelper.class.getClassLoader (). getResourceAsStream ("Person2.xml")); Element element = Document.getdocumentelement ();  NodeList NodeList = element.getelementsbytagname ("person"), for (int i = 0; i < nodelist.getlength (); i++) {element node = (Element) nodelist.item (i); Personbean bean = new Personbean (); Bean.setid (Integer.valueof (Node.getattribute ("id")); NodeList List2 = Node.getchildnodes (); for (int j = 0; J < List2.getlength (); j + +) {node Element2 = List2.item (j); <sp An style= "color: #ff6600;" >//the type of the child note is element Note</span>if (element2.getnodetype () = = Node.element_node) {element childelement = (element ) element2;if ("Name". Equals (Childelement.getnodename ())) {Bean.setname (chilDelement.<span style= "color: #ff6600;" >getFirstChild</span> (). Getnodevalue ());} if ("Age". Equals (Childelement.getnodename ())) {Bean.setage (Childelement.<span style= "color: #ff6600;" >getFirstChild</span> (). Getnodevalue ());}} List.add (bean);}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} return list;}

Second, pull

public static list<personbean> Getpersonbeans () {list<personbean> List = Null;boolean F = false; Personbean bean = null; Xmlpullparserfactory pullparserfactory;try {pullparserfactory = Xmlpullparserfactory.newinstance (); Xmlpullparser parser = Pullparserfactory.newpullparser ();p arser.setinput (PullPaserHelper.class.getClassLoader (). getResourceAsStream ("Person3.xml"), "Utf-8"); int tag = Parser.geteventtype (); while (tag! = Xmlpullparser.end_document {switch (TAG) {Case XmlPullParser.START_DOCUMENT:list = new arraylist<personbean> (); break;case XmlPullParser.START_TAG:String str = parser.getname (), if (Str.equals ("person")) {bean = new Personbean (); Bean.setid ( Integer.valueof (parser.getattributevalue (0))); F = true;} if (f&&bean!=null) {if ("name". Equals (str)) {Bean.setname (Parser.nexttext ());} if ("Age". Equals (str)) {Bean.setage (Parser.nexttext ());}} Break;case XmlPullParser.END_TAG:String con = parser.getname (); if (Con.equals ("person") && bean! = null) { List.add (Bean); bean = Null;f = false;} Break;default:break;} Tag = Parser.next ();}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} return list;}

Third, SAX

public class Saxhanderhelper extends DefaultHandler {list<personbean> Personbeans; String tag;public list<personbean> Getpersonbeans () {return personbeans;} Public Saxhanderhelper () {//TODO auto-generated constructor Stubpersonbeans = new arraylist<personbean> ();} Personbean bean; @Overridepublic void startelement (String uri, String localname, String qName,//Here Gets the properties of the label and label attributes attributes) throws Saxexception {//TODO auto-generated method Stubif (localname.equals ("person")) {bean = new Personbean ( ); for (int i = 0; i < attributes.getlength (); i++) {Bean.setid (integer.valueof (Attributes.getvalue (i)));}} tag = LocalName;} @Overridepublic void EndElement (String uri, String localname, String qName) throws Saxexception {//TODO auto-generated met Hod stubif (localname.equals ("person") && bean! = null) {Personbeans.add (bean); bean = null;} tag = null;} @Overridepublic void characters (char[] ch, int start, int length)//Get the value of the tag here throws Saxexception {//TODO Auto-generaTed Method Stubstring content = new String (CH, start, length). Trim (); if (tag! = null) {if (Tag.equals ("Age")) {Bean.setage (content);} if (tag.equals ("name")) {bean.setname (content);}}}}

Call Method:

SAXParser saxparser = Factory.newsaxparser (); Saxhanderhelper handerhelper = new Saxhanderhelper (); Saxparser.parse (getInputStream (), handerhelper); list<personbean> beans = Handerhelper.getpersonbeans ();



"Android Advanced" XML file DOM, SAX, pull three parsing methods of the full solution

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.