Android series (8): parses and generates XML content using the Pull parser

Source: Internet
Author: User

Android series (8): parses and generates XML content using the Pull parser

In some cases, the application data is stored in the XML file format, so we need to know how to read the data from the XML file.

In Android, XML files can be parsed through SAX, DOM, and pull.

This article mainly introduces the use of the Pull parser to parse and generate XML content.

Introduction: The Pull parser has been integrated in Android, so no jar files need to be added. Xml files used in Android are parsed using the Pull parser.


I. Use the Pull parser to parse XML file content

First, we need to create an Android Project named xml. MainActivity. java is generated by default. In the cn. itcast. xml package, the content in this java file is automatically generated.


Then, we create an xml file: person. xml in the src directory:

  
 
 
  
   
    
Zhangsan
   30
  
  
   
    
Lisi
   25
  
 
The xml file contains two persons.


Next, we need to create a javabean to reflect the xml file, Person. java (note that the attributes in this bean must correspond to those in xml, otherwise they cannot be parsed correctly ):

package cn.itcast.domain;public class Person {private Integer id;private String name;private Integer age;@Overridepublic String toString() {return "Person [id=" + id + ", name=" + name + ", age=" + 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 Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}}
In this java file, we define three attributes: id, name, and age, and generate a toString () method.


After the entity class is created, we need to write the class at the business layer. PersonService. java:

Package cn. itcast. service; import java. io. inputStream; import java. util. arrayList; import java. util. list; import cn. itcast. domain. *; import org. xmlpull. v1.XmlPullParser; import org. xmlpull. v1.XmlPullParserFactory; import android. util. xml; public class PersonService {public static List
 
  
GetPersons (InputStream xml) throws Exception {List
  
   
Persons = null; Person person = null; // obtain the parser. * This method has the same function as the following method. You can obtain the Parser: XmlPullParser pullParser = XmlPullParserFactory. newInstance (). newPullParser (); */XmlPullParser pullParser = Xml. newPullParser (); pullParser. setInput (xml, "UTF-8"); // set the XML data int event = pullParser for the Pull parser. getEventType (); // generates the first event: start documentwhile (event! = XmlPullParser. END_DOCUMENT) {switch (event) {// judge the event case XmlPullParser. START_DOCUMENT: persons = new ArrayList
   
    
(); Break; case XmlPullParser. START_TAG: if ("person ". equals (pullParser. getName () {int id = new Integer (pullParser. getAttributeValue (0); person = new Person (); person. setId (id);} if ("name ". equals (pullParser. getName () {String name = pullParser. nextText (); person. setName (name);} if ("age ". equals (pullParser. getName () {int age = new Integer (pullParser. nextText (); person. setAge (age);} break; case XmlPullParser. END_TAG: if ("person ". equals (pullParser. getName () {persons. add (person); person = null;} break;} event = pullParser. next () ;}return persons ;}}
   
  
 
This code is troublesome. Let's analyze it in detail:

XmlPullParser pullParser = Xml. newPullParser (); this code is used to get a Pull parser. In addition, XmlPullParser pullParser = XmlPullParserFactory. newInstance (). newPullParser (); you can also get the Pull parser.

PullParser. setInput (xml, "UTF-8"); used to set the encoding format of the xml file to be parsed, here is the "UTF-8"

Because the Pull parser is a process of traversing documents This start document event startsEnd.

Int event = pullParser. getEventType (); at this time, the document is initialized. Here, the start document of the document is obtained, which is the START_DOCUMENT event.

Then, it is a while loop, the condition is event! = XmlPullParser. END_DOCUMENT: if the current traversal node does not reach the end, the while loop is executed.

In the while LOOP, a switch () control statement is used to control which node is selected. There are three cases:

Case XmlPullParser. START_DOCUMENT: meets the START_DOCUMENT event (beginning with the xml file)

Case XmlPullParser. START_TAG: satisfies the requirements of the START_TAG event (that is, the start of the xml Element Node: )

Case XmlPullParser. END_TAG: satisfies the END_TAG event (that is, the end of the xml Element Node: for example)

In the second case, we made three judgments:

If ("person". equals (pullParser. getName (): if the person element node is reached, the id is assigned to the person

If ("name". equals (pullParser. getName (): if the name element node is reached, the name is assigned to the person

If ("age". equals (pullParser. getName (): if the age element node is reached, the age is assigned to the person


Note that after each switch () control statement ends, an event = pullParser. next () indicates pointing the Pull parser pointer to the next node.



Above, we have completed the Pull parser, And then we write a test class:

Note: first configure AndroidManfiest. xml to introduce the test syntax, which is not mentioned here.

Compile PersonServiceTest. java and place it in the directory of cn. itcast. test:

Package cn. itcast. test; import java. io. inputStream; import java. util. list; import cn. itcast. domain. person; import cn. itcast. service. personService; import android. test. androidTestCase; import android. util. log; public class PersonServiceTest extends AndroidTestCase {private static final String TAG = "PersonServiceTest"; public void testPersons () throws Exception {// use the getClassLoader () method to obtain the person in the src directory. inputStream xml = this. getClass (). getClassLoader (). getResourceAsStream ("person. xml "); List
 
  
Persons = PersonService. getPersons (xml); for (Person person: persons) {Log. I (TAG, person. toString ());}}}
 
Then, we add a filter on the LogCat page:

You can print out persons on the LogCat page.


<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPGgyPrb + release + rPJWE1MzsS8/qO6PC9wPgo8cD48cHJlIGNsYXNzPQ = "brush: java; ">/*** save data * @ param persons data * @ param out output direction * @ throws Exception */public static void save (List Persons, OutputStream out) throws Exception {XmlSerializer serializer = Xml. newSerializer (); // get the serializer of the instantiate. setOutput (out, "UTF-8"); // sets the output stream encoding format serializer. startDocument ("UTF-8", true); // sets START_DOCUMENT, which is the beginning of the xml serializer. startTag (null, "persons"); // start the first persons tag for (Person person: persons) {serializer. startTag (null, "person"); serializer. attribute (null, "id", person. getId (). toString (); serializer. startTag (null, "name"); serializer. text (person. getName (); serializer. endTag (null, "name"); serializer. startTag (null, "age"); serializer. text (person. getAge (). toString (); serializer. endTag (null, "age"); serializer. endTag (null, "person");} serializer. endTag (null, "persons"); serializer. endDocument (); out. flush (); out. close ();}Then, we add a method to the test class PersonServiceTest. java:

Public void testSave () throws Exception {List
 
  
Persons = new ArrayList
  
   
(); Persons. add (new Person (43, "zhangxx", 80); persons. add (new Person (24, "lisi", 80); persons. add (new Person (12, "wangwu", 80); // put File xmlFile = new File (getContext () in the/files directory (). getFilesDir (), "itcast. xml "); // open the output stream FileOutputStream outStream = new FileOutputStream (xmlFile); PersonService. save (persons, outStream); // call the save () method to generate an xml file}
  
 
We can generate an itcast. xml file in the files directory.










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.