The use of Pull parser in XML parsing mode

Source: Internet
Author: User

XML has a number of parsing methods, this article only describes using the pull parser to parse the XML file, and then I'll explain using the pull parser to read the XML file contents and create a new XML file.

  1. reading the contents of an XML file
    I have added an XML file to the project, "Data.xml", the following is the contents of the XML file.
    <?xml version= "1.0" encoding = "Utf-8"?><persons> <person    id = "All" >        <name>jack</ name>        <age>18</age>    </person>    <person id = "All" >        <name>tom</ name>        <age>21</age>    </person></persons>
    for ease of operation, I created a new person class:

    public class Person {private int id;private String name;private int 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 int getage () {return age;} public void Setage (int.) {this.age = age;} @Overridepublic String toString () {return "person [id=" + ID + ", name=" + name + ", age=" + Age + "]";} public person (int ID, String name, Int. age) {super (); this.id = Id;this.name = Name;this.age = age;} Public person () {}}

    then I built a Personservice class that implements our operations in this class.
    public class Personservice {/** * Gets the contents of the XML file * @param p_inputstreamxml file input stream * @return A list containing person information * @throws Exception */p Ublic static list<person> getpersons (InputStream p_inputstream) throws exception{list<person> persons = Null Person person = null;//gets Xmlpullparse object Xmlpullparser pullparser = Xml.newpullparser ();p ullparser.setinput (p_ InputStream, "Utf-8"); int event = Pullparser.geteventtype (); while (event! = xmlpullparser.end_document) {switch (event) {Case XmlPullParser.START_DOCUMENT:persons = new arraylist<person> (); Break;case XmlPullParser.START_TAG:if (" Person ". Equals (Pullparser.getname ())) {person = new person (); int id = new Integer (pullparser.getattributevalue (0)); Person.setid (ID);} if ("Name". Equals (Pullparser.getname ())) {String name = Pullparser.nexttext ();p erson.setname (name);} if ("Age". Equals (Pullparser.getname ())) {int. = new Integer (Pullparser.nexttext ());p erson.setage (age);} Break;case XmlPullParser.END_TAG:if ("person". Equals (Pullparser.getname ())) {persons. Add (person);p Erson = null;} break;} event = Pullparser.next ();} return persons;} /** * Save data to XML file * @param p_person data list * @param p_out output stream * @throws exception throws exception */public static void Save (List<perso N> P_person,outputstream p_out) throws Exception{xmlserializer serializer = Xml.newserializer (); Serializer.setoutput (P_out, "Utf-8"); Serializer.startdocument ("Utf-8", true); Serializer.starttag (null, "persons") ; for (person Person:p_person) {Serializer.starttag (null, ' person '); Serializer.attribute (NULL, "id", Person.getid () + " "); Serializer.starttag (null," name "); Serializer.text (Person.getname ()); Serializer.endtag (null," name "); Serializer.starttag (NULL, "age"); Serializer.text (Person.getage () + ""); Serializer.endtag (null, "age"); Serializer.endtag (null, "person");} Serializer.endtag (NULL, "persons"), Serializer.enddocument ();p _out.flush ();p _out.close ();}}

    in this class, I have defined two static methods, one to read the contents of the XML file, then put the information into a list, and another to generate an XML file, saved to the phone.
    When we read the XML, we need to get the Xmlpullparser object first, using a static method of the XML class to get: Xml.newpullparser (), We then set the XML file input stream and the Xmlpullparse object to either Connect: Pullparser.setinput (p_inputstream, "Utf-8") and then start parsing the XML file.
    Parsing is a line-by-row parsing, int event = Pullparser.geteventtype (), this line of code may not be understood at the beginning, for example, the parser parsing the content is <person id = ""; Then the value of the event is Xmlpullparser.start_tag, which represents the start tag, some other values in the code,end_tag--> the end tag, and so on. Based on the value of the event, we can know which line the parser is currently parsing, and then do the related operations.

  2. Create a new XML file and save it to your phone
When you create a new Xml file, you also use the wrapper class, XmlSerializer serializer = Xml.newserializer (), so that we manipulate the objects of the XmlSerializer, Then you can save the information to your phone.

below is the code in my mainactivity:

public class Mainactivity extends Activity {private TextView text; StringBuilder sb; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); text = (TextView) Findviewbyid (r.id.text); sb = new StringBuilder (); Sb.append ( "Contents of the source file \ n"); InputStream xml = GetClass (). getClassLoader (). getResourceAsStream ("Data.xml"); try {list<person> Persons = Personservice.getpersons (XML), for (person person:persons) Sb.append (person.tostring ()). Append ("\ n"); Text.settext (SB);} catch (Exception e) {}sb.append ("contents of the newly created file \ n"); list<person> p = new arraylist<person> ();p. Add (new person (45, "Lili"));p. Add (The new person, "Liufi",) ); File XMLFile = new file (Getapplicationcontext (). Getfilesdir (), "person.xml"); try {outputstream outputstream = new FileOutputStream (xmlfile); Personservice.save (P, outputstream);} catch (Exception e) {}try {xml = new FileInputStream (Getapplicationcontext (). Getfilesdir () + "/person.xml"); List<person> persons = Personservice.getpersons (XML), for (int i=0;i<persons.size (); i++) Sb.append (Persons.get (i). ToString ()). Append ("\ n"); Text.settext (SB);} catch (Exception E1) {}}}
wrote thecontent is not much, code is quite a lot of, because the content of the basis, so look at the code can understand the way of parsing, multi-use can quickly grasp the pull parser.

The use of Pull parser in XML parsing mode

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.