Getting started with Android: parsing XML with pull

Source: Internet
Author: User
Document directory
  • Application: Create the person. xml file mentioned above to/data/package/files.
I. Introduction to pull parser

Pull Parsing is similar to sax \ Dom and is used to parse XML;

Ii. Use the pull parser to read XML data

The template code is as follows:

Xmlpullparser parser = xml. newpullparser (); // create a pull parser. setinput (in, "UTF-8"); // The read encoding is UTF-8int event = parser. geteventtype (); // call while (event! = Xmlpullparser. end_document) {// parser. getname (); // obtain the name of the tag to which the current tag is directed. // parser. getattributevalue (0); // obtain the 1st attribute values of the current tag. // parser. nexttext (); // obtain the tag value of the current tag switch (event) {Case xmlpullparser. start_document: // if it points to start_document // process break; Case xmlpullparser. start_tag: // if it is directed to start_tag // process break; Case xmlpullparser. end_tag: // if it points to end_tag // process break;} event = parser. next (); // point to the next tag}

Application: Read the person. xml file in the/data/package/files/directory.

The XML file is as follows:

<?xml version="1.0" encoding="UTF-8"?><persons>    <person id="1">        <name>xiazdong-1</name>        <age>20</age>    </person>    <person id="2">        <name>xiazdong-2</name>        <age>30</age>    </person></persons>

As shown above, <person> </person> can be considered as a JavaBean, while <persons> </persons> forms a person queue;

Therefore, we create a person JavaBean:

package org.xiazdong.vo;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 age) {this.age = age;}public Person(int id, String name, int age) {this.id = id;this.name = name;this.age = age;}public Person() {}@Overridepublic String toString() {return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";}}

Next, we will write the following readxml method to convert the data in the XML file into a person queue;

Public class xmlservice {public list <person> readxml (inputstream in) throws exception {xmlpullparser parser = xml. newpullparser (); parser. setinput (in, "UTF-8"); List <person> List = NULL; person = NULL; int event = parser. geteventtype (); // start parsing and obtain the event/** optional events include: * (1) start_document * (2) end_document * (3) start_tag * (4) end_tag **/while (event! = Xmlpullparser. end_document) {Switch (event) {Case xmlpullparser. start_document: List = new arraylist <person> (); break; Case xmlpullparser. start_tag: If ("person ". equals (parser. getname () {person = new person (); int id = integer. parseint (parser. getattributevalue (0); person. setid (ID);} If ("name ". equals (parser. getname () {person. setname (parser. nexttext ();} If ("age ". equals (parser. getname () {person. setage (integer. parseint (parser. nexttext ();} break; Case xmlpullparser. end_tag: If ("person ". equals (parser. getname () list. add (person); break;} event = parser. next (); // read the next} return list ;}}

After writing this method, we can test this method:

public class XmlTest extends AndroidTestCase{private static final String TAG = "XmlTest";public void testRead() throws Exception{XmlService service = new XmlService();List<Person> list = service.readXml(this.getContext().openFileInput("person.xml"));Log.i(TAG, String.valueOf(list.size()));for(Person p:list){Log.i(TAG, p.toString());}}}

The running effect is as follows:

3. Use the serializer parser to write XML files

The core code is as follows:

Xmlserializer serializer = xml. newserializer (); // create a serializer parser serializer. setoutput (Out, "UTF-8"); // set the encoding of the output stream and output to UTF-8serializer.startDocument ("UTF-8", true); // output start document <? XML version = "1.0" encoding = "UTF-8" standalone = "true"?> Serializer. starttag (null, "tagname"); // output <tagname> serializer. attribute (null, "name", "value"); // output <tagname = "value"> serializer. text ("value"); // output <tagname> </tagname> serializer. endtag (null, "tagname"); // end label serializer. enddocument (); // end document

Application: Create the person. xml file mentioned above to/data/package/files. The following code is used to write the person queue to the output stream file (this is the file output stream)

public class XmlService {public void writeXml(List<Person> list,OutputStream out)throws Exception{XmlSerializer serializer = Xml.newSerializer();serializer.setOutput(out, "UTF-8");serializer.startDocument("UTF-8", true);serializer.startTag(null, "persons");for(Person p:list){serializer.startTag(null,"person");serializer.attribute(null, "id", String.valueOf(p.getId()));serializer.startTag(null, "name");serializer.text(p.getName());serializer.endTag(null, "name");serializer.startTag(null, "age");serializer.text(p.getAge()+"");serializer.endTag(null, "age");serializer.endTag(null, "person");}serializer.endTag(null, "persons");serializer.endDocument();out.flush();out.close();}}

The test code is as follows:

public class XmlTest extends AndroidTestCase{public void testWrite()throws Exception{XmlService service = new XmlService();List<Person> list = new ArrayList<Person>();for(int i=0;i<3;i++){Person p = new Person();p.setId(i);p.setName("xiazdong-"+i);p.setAge(20+i);list.add(p);}OutputStream out = this.getContext().openFileOutput("person.xml", Context.MODE_PRIVATE);service.writeXml(list, out);}}

Conclusion: Use the pull parser to read data and use serializer to write data;

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.