Android uses pull, sax to parse xml, androidpull

Source: Internet
Author: User

Android uses pull, sax to parse xml, androidpull
Pull parses xml files

1. Get reference of XmlpullParser class

There are two methods

// Parser factory XmlPullParserFactory factory = XmlPullParserFactory. newInstance (); XmlPullParser pullParser = factory. newPullParser ();

// Directly obtain the instance
XmlPullParser pullParser = Xml. newPullParser ();

2. Set resolution content

The setInput method is used to set the resolution content to be rewritten. It is clear that the xml file is read to Reader or InputStream. Note that the encoding must be specified for InputStream.

 pullParser.setInput(getAssets().open("student.xml"),"utf-8");

GetAssets (). open ("student. xml") returns an InputStream byte stream. Therefore, you must specify the encoding format.

 

3. Get the current event type and start Parsing

START_DOCUMENT

END_DOCUMENT end reading the document

START_TAG

END_TAG end read tag

 

 

Xml data

1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <persons> 3 <person id = "1"> 4 <name> Zhang San </name> 5 <age> 23 </age> 6 </person> 7 <person id = "2"> 8 <name> Li Si </name> 9 <age> 23 </age> 10 </person> 11 </persons>

 

Pull parse core code

1 try {2 // parser factory 3 XmlPullParserFactory factory = XmlPullParserFactory. newInstance (); 4 // create parser 5 XmlPullParser pullParser = factory. newPullParser (); 6 // directly create the parser 7 // pullParser = Xml. newPullParser (); 8 // set the resolution content 9 // getAssets (). open ("student. xml ") returns a byte stream InputStream. Therefore, you must specify the encoding format 10 pullParser. setInput (getAssets (). open ("student. xml ")," UTF-8 "); 11 // start parsing 12 // get the currently resolved tag 13 // get the current event type: start reading the document and start reading the tag, end tag. The end reader is similar to the end reader. Status 14 int type = pullParser. getEventType (); 15 while (type! = XmlPullParser. END_DOCUMENT) {16 switch (type) {17 // starts reading the document 18 case XmlPullParser. START_DOCUMENT: 19 break; 20 // start to read tag 21 case XmlPullParser. START_TAG: 22 String tag = pullParser. getName (); // get node name 23 if (tag. equals ("person") {24 person = new Person (); 25 // get node attribute 26 String id = pullParser. getAttributeValue ("", "id"); 27 if (TextUtils. isEmpty (id) continue; 28 person. setId (Integer. parseInt (id); 29} else if (tag. equals ("name") {30 // get the next text 31 String name = pullParser. nextText (); 32 if (TextUtils. isEmpty (name) continue; 33 person. setName (name); 34} else if (tag. equals ("age") {35 String age = pullParser. nextText (); 36 if (TextUtils. isEmpty (age) continue; 37 person. setAge (Integer. parseInt (age); 38} 39 break; 40 // end read tag 41 case XmlPullParser. END_TAG: 42 tag = pullParser. getName (); 43 // Add to list44 if (tag. equals ("person") {45 persons. add (person); 46} 47 break; 48 // end reading document 49 case XmlPullParser. END_DOCUMENT: 50 break; 51} 52 // read the next event 53 type = pullParser. next (); 54} 55} catch (XmlPullParserException e) {56 e. printStackTrace (); 57} catch (IOException e) {58 e. printStackTrace (); 59}

Here I will mentionGetAttributeValue () method to obtain the node attributes. There are two parameters. The first parameter represents the namespace. What is xml in The namespace? Generally, xmlns is added to the root element of an xml file. This defines the namespace.

After a namespace is added to an attribute, it indicates that the attributes of the namespace are similar to the package name but are not commonly used.

 



Parse xml data using SAX
Sax performs sequential scanning of documents when scanning
The end of the document, the end of the element, and the end of the tag will trigger the event.
The use of sax is almost the same as that of pull. I personally prefer to use a little more.
Sax is implemented through the override method, and the callback will be triggered when the conditions are met. These methods are defined in the ContentHandler interface. Android provides a help class for us.
DefaultHandler, only need to inherit this class, the rewrite method is OK
Core code
  
1 try {2 // create a SAX Parser 3 SAXParserFactory factory = SAXParserFactory. newInstance (); 4 SAXParser parser = factory. newSAXParser (); 5 // customize a Handler parser 6 PersonHandler handler = new PersonHandler (); 7 // The parser parses xml 8 parser. parse (getAssets (). open ("student. xml "), handler); 9 for (Person p: handler. getPersonList () {10 Log. e ("XmlSAXParser", p. getName () + "====" + p. getAge () + "==========" + p. getId (); 11} 12} catch (ParserConfigurationException e) {13 e. printStackTrace (); 14} catch (SAXException e) {15 e. printStackTrace (); 16} catch (IOException e) {17 e. printStackTrace (); 18}

 

Parser code
 
1 public class PersonHandler extends DefaultHandler {2 // save data 3 private List <Person> personList; 4 private Person person Person; 5 // node name currently resolved element name 6 private String tag; 7 8/** 9 * read the text content from the xml file 10 * @ param ch string content 11 * @ param start position 12 * @ param length 13 * @ throws SAXException14 */15 @ Override16 public void characters (char [] ch, int start, int length) throws SAXException {17 super. characters (ch, s Tart, length); 18 // create String 19 String text = new String (ch, start, length ). trim (); 20 // The string cannot be empty, neither empty text nodes are read, such as line feed 21 if (TextUtils. isEmpty (text) return; 22 // value 23 if ("name ". equals (tag) {24 person. setName (text); 25} else if ("age ". equals (tag) {26 person. setAge (Integer. parseInt (text )); 27} 28} 29 30/** 31*32 * @ param uri the namespace does not use the 33 * @ param localName prefix. The tag name does not use the 34 * @ param qName node name 35 *@ param attribute S attribute set 36 * @ throws SAXException37 */38 @ Override // qName attributes39 public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException {40 super. startElement (uri, localName, qName, attributes); 41 tag = qName; 42 // Why to create a set and an object, please refer to the xml above for careful analysis 43 if ("persons ". equals (qName) {44 // set of data storage 45 personList = new ArrayList <> (); 46} else if ("person ". equals (qName) {47 pers On = new Person (); 48 String id = attributes. getValue ("id"); 49 if (! TextUtils. isEmpty (id) {50 person. setId (Integer. parseInt (id); 51} 52} 53} 54 55 @ Override 56 public void endElement (String uri, String localName, String qName) throws SAXException {57 super. endElement (uri, localName, qName); 58 if ("person ". equals (qName) {59 personList. add (person); 60} 61} 62 63}

 

Methods such as startElement startDocument endDocument

In a few days, we will organize a simple Demo of xml and listview.

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.