Java Collection 3----XML parsing (3) StAX PULL parsing, 3 ---- xmlstax

Source: Internet
Author: User

Java Collection 3----XML parsing (3) StAX PULL parsing, 3 ---- xmlstax

Parse XML using PULL:

Pull is an implementation of STAX.

StAX is short for The Streaming API for XML. It is an API that uses The pull mode to parse (pull-parsing) XML documents.

StAX provides an Iterator-based API for programmers to control the xml document parsing process.

Why is the StAX method more efficient than SAX?

Because SAX is in Push mode, all operations are performed under the automatic control of the parser, and all events are processed. The parser automatically starts the parsing task no matter the entire document needs to be parsed, the resolution is performed sequentially until the resolution is complete. While StAX is in PULL mode, the user can control the event type and time to terminate the parsing task as needed. The user calls next () and the parser performs a downward parsing, the parsing operation is completely under the control of the user. You can terminate the parsing at any time when the required Parsing is completed.

 

Simply put, the push mode means that you can tell the parser how to perform the operation. Then, the parser automatically completes all the parsing tasks and you cannot interfere with them.

The pull mode is like drawing paper. It is pulled as needed. It will not be automatically launched if it is not needed. You can pull a box of paper all the time, or just pull a few as needed.

 

Third-party jar packages for PULL parsing can be downloaded from the Internet to use PULL to parse XML

Three types of PULL implementations can be downloaded on www.xmlpull.org:

 

From the description, we can see that the implementation of XPP3 is mainly aimed at performance and ease of use. Moreover, the android built-in PULL parser seems to be XPP3, so you can download this implementation, to parse the PULL of XML.

Select an appropriate XPP3 download:

 

For example, I downloaded:

 

After the download is complete, decompress, and find the file name is similar to the jar package of the xpp3-1.1.4c.jar, there is the API we need.

The api help manual is stored in the API directory in the doc directory. You can refer to this manual to learn how to use the XPP3 PULL parser.

 

Like DOM and SAX parsing XML, PULL parsing XML also uses the parser factory class XmlPullParserFactory, And the parser class XmlPullParser, XPP3 also provides the XmlSerializer class for serializing memory objects to xml documents.

 

The factory class also obtains the factory class object through the static method newInstance.

 

The newPullParser () and newSerializer () methods are used to obtain the XmlPullParser object and XmlSerializer object respectively.

The preceding three methods are commonly used in the factory class.

 

XmlPulParser uses the setInput () method to set the XML document to be parsed.

 

Call the next method to parse data step by step

 

Call the getEventType () method to confirm the event type triggered by the current parsing XML.

The event type is identified by several constants defined in XmlPullParser:

START_DOCUMENT: triggers parsing.

START_DOCUMENT: triggered when a node is hit

TEXT: triggered when reading character TEXT

END_TAG: triggered when an end node is reached

END_DOCUMENT: triggered when resolution is complete

If the trigger event type is START_TAG or END_TAG, you can use the getName () method to obtain the name of the current node.

 

If the event type is START_TAG, you can use nextText () to obtain the content of the subnode. If the event type is END_TAG, an empty string is returned.

 

When the event type is START_TAG, you can use the getAttributeCount () method to obtain the number of attributes of the node.

You can use the getAttributeName (int index) method to obtain the name of the attribute of the specified index.

 

You can use the getAttributeValue (int index) method to obtain the value of the specified index attribute.

The above are several common methods in the XmlPullParser class.

 

XmlSerializer can serialize data in memory to XML documents. There are also several common methods:

SetOutput () method, which specifies the XML file to which the data is serialized

 

StartDocument () method, specifying the start of an XML document <? Xml declaration information

For example, startDocument ("UTF-8", true); The following information is output in the XML document:

<? Xml encoding = "UTF-8" standalone = "yes"?>

StartTag () starts a node. namespace does not exist. It is generally set to null or an empty string.

 

Text () set text content

 

EndTage () ends a node.

 

Attribute () sets the node attributes.

 

After learning about the common methods of these classes, you can implement XML parsing and serialization in the PULL mode. However, there is now a question: can the DOM add, delete, modify, and query operations be performed? Can the PULL mode be used?

In DOM mode, the entire document object is in the memory, so you can implement modification and write-back. However, in both the PULL mode and the SAX mode, the memory is parsed and released, and the addition, deletion, modification, and query operations cannot be directly implemented. However, you can imitate the DOM mode and save the parsed part in the memory. For example, you can save all parsed objects to a List. All addition, deletion, modification, and query operations are performed on the List object. After all operations are completed, the List of the final version in the memory is serialized into the Xml document, in the PULL mode, add, delete, modify, and query operations are indirectly implemented.

For specific operations, refer to the following code:

Students. xml to be parsed:

 1 <?xml version="1.0" encoding="UTF-8" standalone="no"?> 2  3 <students> 4  5     <student id="000"> 6  7         <name>zhangsan22</name> 8  9         <gender>female</gender>10 11         <age>26</age>12 13     </student>14 15     <student id="002">16 17         <name>lisi</name>18 19         <gender>male</gender>20 21         <age>24</age>22 23     </student>24 25     <student id="003">26 27         <name>xiaoqiao</name>28 29         <gender>female</gender>30 31         <age>18</age>32 33     </student>34 35     <student id="004">36 37         <name>diaochan</name>38 39         <gender>female</gender>40 41         <age>23</age>42 43     </student>44 45 </students>

Corresponding entity class: Student. java:

 1 package cn.csc.bean; 2  3 public class Student { 4  5          private String id = null; 6  7          private String name = null; 8  9          private String gender = null;10 11          private int age = 0;12 13          public String getId() {14 15                    return id;16 17          }18 19          public void setId(String id) {20 21                    this.id = id;22 23          }24 25          public String getName() {26 27                    return name;28 29          }30 31          public void setName(String name) {32 33                    this.name = name;34 35          }36 37          public String getGender() {38 39                    return gender;40 41          }42 43          public void setGender(String gender) {44 45                    this.gender = gender;46 47          }48 49          public int getAge() {50 51                    return age;52 53          }54 55          public void setAge(int age) {56 57                    this.age = age;58 59          }60 61          public Student(String id, String name, String gender, int age) {62 63                    super();64 65                    this.id = id;66 67                    this.name = name;68 69                    this.gender = gender;70 71                    this.age = age;72 73          }74 75          public Student() {76 77                    super();78 79          }80 81          public String toString() {82 83                    return "[id:"+id+",name:"+name+",gender:"+gender+",age"+age+"]";84 85          }86 87 }

 

The StudentPullUtils class implements two methods: one is used to parse the student in the xml file to the List <Student>, and the other is used to serialize the data in the List <Student> to the specified xml file:

  1 public class StudentPullUtils {  2   3          public static List<Student> parseXml(String filename) throws Exception{  4   5                    List<Student> list = new ArrayList<Student>();  6   7                    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();  8   9                    XmlPullParser parser = factory.newPullParser(); 10  11                    parser.setInput(new FileInputStream(filename), "utf-8"); 12  13                    int eventType; 14  15                    Student s = null; 16  17                    while((eventType = parser.getEventType())!= XmlPullParser.END_DOCUMENT){ 18  19                             if(eventType == XmlPullParser.START_TAG && parser.getName().equals("student")){ 20  21                                      s = new Student(); 22  23                                      s.setId(parser.getAttributeValue(0)); 24  25                             } 26  27                             if(eventType == XmlPullParser.START_TAG && parser.getName().equals("name")){ 28  29                                      s.setName(parser.nextText()); 30  31                             } 32  33                             if(eventType == XmlPullParser.START_TAG && parser.getName().equals("age")){ 34  35                                      s.setAge(Integer.parseInt(parser.nextText())); 36  37                             } 38  39                             if(eventType == XmlPullParser.START_TAG && parser.getName().equals("gender")){ 40  41                                      s.setGender(parser.nextText()); 42  43                             } 44  45                             if(eventType == XmlPullParser.END_TAG && parser.getName().equals("student")){ 46  47                                      list.add(s); 48  49                             } 50  51                             parser.next(); 52  53                    } 54  55                    return list; 56  57          } 58  59          60  61          public static boolean serializeList(List<Student> list, String filename) throws Exception{ 62  63                    XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 64  65                    XmlSerializer serializer = factory.newSerializer(); 66  67                    serializer.setOutput(new FileOutputStream(filename), "utf-8"); 68  69                    serializer.startDocument("utf-8", true); 70  71                    serializer.startTag(null, "students"); 72  73                    for(Student s : list){ 74  75                             serializer.startTag(null, "student"); 76  77                             serializer.attribute(null, "id", s.getId()); 78  79                             serializer.startTag(null, "name"); 80  81                             serializer.text(s.getName()); 82  83                             serializer.endTag(null, "name"); 84  85                             serializer.startTag(null, "gender"); 86  87                             serializer.text(s.getGender()); 88  89                             serializer.endTag(null, "gender"); 90  91                             serializer.startTag(null, "age"); 92  93                             serializer.text(s.getAge()+""); 94  95                             serializer.endTag(null, "age"); 96  97                             serializer.endTag(null, "student"); 98  99                    }100 101                    serializer.endTag(null, "students");102 103                    serializer.endDocument();104 105                   106 107                    return true;108 109          }110 111 }

 

Call the test: to read data from students. xml to Lis <Student>, add 1 to the Age of all students, and serialize the data to students_bak.xml:

1 List<Student> list = StudentPullUtils.parseXml("students.xml");2 3 for(Student s: list){4 5          s.setAge(s.getAge()+1);6 7 }8 9 StudentPullUtils.serializeList(list, "students_bak.xml");

 

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.