XML file parsing (pull) for Android small function implementation

Source: Internet
Author: User

There are three kinds of pull, SAX, and Dom three ways that are common to Android parsing XML.
The most commonly used is the pull that the Pull,android project itself parses XML with.
Pull is an open source project whose official website is: http://xmlpull.org/.
The pull project has been integrated in the Android project and can be used directly.


Create a new Android project.


Add a test file

Create a new raw folder in the Res directory, where you add the file Persons.xml, as follows:

<?xml version= "1.0" encoding= "UTF-8"?><persons>    <person id = "1010" >        <name>a</ name>        <age>10</age>    </person>    <person id = "1111" >        <name>b</ name>        <age>11</age>    </person></persons>

Two layouts
Open the Main.xml to modify the contents as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:orientation=" vertical "    android:layout_width=" fill_parent "    android:layout_height=" Fill_parent ">    <textview android:layout_width=" fill_parent "        android:layout_height=" Fill_parent "        android:id= "@+id/content"/></linearlayout>

Used to display data parsed from the XML.


Three Add entity classes
To create a new person class, save the read data with the following class capacity:

public class Person {    private Integer ID;    private String name;    Private Integer age;    public void SetId (Integer id) {        this.id = ID;    }    public void Setage (Integer age) {        this.age = age;    }    public void SetName (String name) {        this.name = name;    }    Public Integer getId () {        return ID;    }    Public String GetName () {        return name;    }    Public Integer Getage () {        return age;    }    @Override public    String toString () {        return "person{" +                "id=" + ID +                ", name= ' + name + ' + ' +                " , age= "+ Age +                '} ';}    }

Four-function implementation
Create a new class Personservice to parse the XML with the complete code as follows:

public class Personservice {/** * Get object list * * @param instream XML file input stream * @return Object list * @throws EXC  Eption */Public list<person> getpersons (InputStream instream) throws Exception {Xmlpullparser parser        = Xml.newpullparser ();            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 Xmlpullparse                        R.start_document://Document Start event, data initialization can be processed persons = new arraylist<person> ();                    Break Case Xmlpullparser.start_tag://start reading a tag//to determine which tag is read by GetName and then get the value of the text node by Nexttext (), or by getattr                            Ibutevalue (i) Gets the attribute node value if (Parser.getname (). Equalsignorecase ("person")) { CurreNtperson = new Person ();                        Currentperson.setid (New Integer (Parser.getattributevalue (NULL, "id"));                            } else if (Currentperson! = null) {String name = Parser.getname (); if (Parser.getname (). Equalsignorecase ("name")) {CURRENTPERSON.SETN                                Ame (Parser.nexttext ());//If it is followed by a text element, that is, return its value} else if (Name.equalsignorecase ("Age")) {                            Currentperson.setage (New Integer (Parser.nexttext ()));                    }} break; Case xmlpullparser.end_tag://End Element event if (Parser.getname (). Equalsignorecase ("person") && cur                            Rentperson = null) {Persons.add (Currentperson);                        Currentperson = null;     } break;           } EventType = Parser.next ();            } instream.close ();        return persons;        } catch (Exception e) {e.printstacktrace ();    } return null; }}

Five Test code
Modify the Mainactivity.java code as follows:

    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);            try {//test with: Read file contents//String str = "XML file contents: \ n";            str + = This.read ("person.xml");            InputStream XML = Getresources (). Openrawresource (r.raw.persons);            String str = "XML file content: \ n";            Personservice service = new Personservice ();            list<person> persons = Service.getpersons (XML);            for (person person:p ersons) str = str + person.tostring () + "\ n";            Xml.close ();            TextView TextView = (TextView) Findviewbyid (r.id.content);        Textview.settext (str);        } catch (Exception e) {e.printstacktrace (); }} public String read (string name) throws exception{InputStream is = Getresources (). Openrawresource (R.raw.        persons);      Bytearrayoutputstream OS = new Bytearrayoutputstream ();  byte[] buf = new byte[1024];        int len = 0;        while (len = Is.read (BUF))! =-1) {Os.write (buf,0, Len);        } byte[] data = Os.tobytearray ();        String content = new string (data);    return content; }

Six Run results





XML file parsing (pull) for Android small function implementation

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.