Android XML parsing-pull

Source: Internet
Author: User

In addition to using Sax and Dom to parse XML files, you can also use the android built-in pull parser to parse XML files. The Running Method of the pull parser is similar to that of the SAX Parser. It provides similar events, such as the start element and end element events. You can use parser. Next () to enter the next element and trigger the corresponding event. The event is sent as a numeric code, so you can use a switch to process the event you are interested in. When parsing an element, call parser. nexttext () to obtain the value of the next text node.

Use the pull parser to read itcast. XML code.

Pull parser source code and documentation download URL: http://www.xmlpull.org/

The XML file to be parsed in this example is as follows:

File Name: itcast. xml
<? XML version = "1.0" encoding = "UTF-8"?>
<Persons>
<Person id = "23">
<Name> liming </Name>
<Age> 30 </age>
</Person>
<Person id = "20">
<Name> lixiangmei </Name>
<Age> 25 </age>
</Person>
</Persons>

The example defines a Javabean to store the XML content parsed above. The Javabean is person. In the MVC design model, JavaBean is also called a model layer. In a general program, we call it a data layer, which is used to set data attributes and some behaviors, then, I will provide the get/set method for obtaining and setting attributes.

Let's take a look at the specific example:

First, create an itcast. the XML file is in the src directory, and a new CN. itcast. domain package, create a person class under the package, mainly used to store the XML content parsed above, JavaBean is a model in the MVC design model, also known as the model layer, in the general program, we call it a data layer, which is used to set data attributes and some behaviors. Then, I will provide the get/set method for getting and setting attributes.

The Code is as follows:

View code

 1 package cn.itcast.domain;
2
3 public class Person {
4 private Integer id;
5 private String name;
6 private Short age;
7
8 public Person(){}
9
10 public Person(Integer id, String name, Short age) {
11 this.id = id;
12 this.name = name;
13 this.age = age;
14 }
15
16 public Integer getId() {
17 return id;
18 }
19 public void setId(Integer id) {
20 this.id = id;
21 }
22 public String getName() {
23 return name;
24 }
25 public void setName(String name) {
26 this.name = name;
27 }
28 public Short getAge() {
29 return age;
30 }
31 public void setAge(Short age) {
32 this.age = age;
33 }
34 @Override
35 public String toString() {
36 return "Person [age=" + age + ", id=" + id + ", name=" + name + "]";
37 }
38
39 }

 

Step 2: Create a package CN. itcast. service package and create a pullpersonservice class under the package. This is the M and service class in MVC. The main code is as follows:

 

View code

1 package CN. itcast. Service;
2
3 Import java. Io. inputstream;
4 Import java. util. arraylist;
5 import java. util. List;
6 Import javax. xml. parsers. saxparser;
7 Import javax. xml. parsers. saxparserfactory;
8 Import org. xml. Sax. attributes;
9 Import org. xml. Sax. saxexception;
10 Import org. xml. Sax. helpers. defaulthandler;
11
12 Import CN. itcast. domain. person;
13 /**
14 * Parse XML content using Sax
15 */
16 public class saxpersonservice {
17 private final class personparser extends defaulthandler {
18 // put all parsed data in the Set
19 private list <person> Persons = NULL;
20 // record the name of the currently resolved Element Node
21 private string tag = NULL;
22 private person = NULL;
23 // provides a getpersons method, mainly used by the main program
24 public list <person> getpersons (){
25 return persons;
26}
27
28 @ override
29 public void startdocument () throws saxexception {
30 // Initialization
31 persons = new arraylist <person> ();
32}
33
34 @ override
35 public void startelement (string Uri, string localname, string QNAME, attributes) throws saxexception {
36 // determine whether it is the element node to be parsed
37 If ("person". Equals (localname )){
38 person = new person (); // new the person object, and pass the content to be parsed to the ID attribute of the person
39 person. setid (New INTEGER (attributes. getvalue (0 )));
40}
41 // store the node name in the member variable
42 tag = localname;
43}
44
45 @ override
46 Public void characters (char [] CH, int start, int length)
47 throws saxexception {
48 // first determine whether the node name is null, and then determine whether the node name is name
49 If (tag! = NULL ){
50 string data = new string (CH, start, length); // obtain the data of the text node
51 if ("name". Equals (TAG) {// determine whether the node name is name
52 person. setname (data); // pass the content to be parsed to the name attribute of the person
53} else if ("Age". Equals (TAG) {// determine whether the node name is age
54 person. setage (new short (data ));
55}
56}
57}
58
59 @ override
60 public void endelement (string Uri, string localname, string QNAME)
61 throws saxexception {
62 if ("person". Equals (localname) {// when the end and end nodes are person
63 persons. Add (person); // put the person in the Set persons
64 person = NULL; // set the current person to null
65}
66 // set the record to null when an end element is encountered
67 tag = NULL;
68}
69}
70}


Step 3: Create a personservicetest class under the main package. This class is equivalent to the C (control layer) in MVC. It mainly tests the pullgetpersons () method of the pullpersonservice class.

 

View code

 1 public class PersonServiceTest extends AndroidTestCase {
2 private static final String TAG = "PersonServiceTest";
3 public void testPullGetPersons() throws Throwable{
4 InputStream inStream = getClass().getClassLoader().getResourceAsStream("itcast.xml");
5 List<Person> persons = PULLPersonService.getPersons(inStream);
6 for(Person person : persons){
7 Log.i(TAG, person.toString());
8 }
9 }
10 }


Step 3: perform a unit test on the textpullgetpersons () method. The input result is

 

 

 

 

 

 

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.