Android development uses PULL to parse and generate XML, androidpull

Source: Internet
Author: User
Tags object serialization

Android development uses PULL to parse and generate XML, androidpull

Android development uses PULL to parse and generate XML

Please respect others' labor achievements. repost the Source: Use PULL for Android development to parse and generate XML

I. Introduction to parsing XML1.PULL using PULL

I used the DOM, SAX, Jdom, and dom4j methods to parse XMl in "several ways of XML parsing. In addition to the preceding method, you can use the Pull parser built in Android 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 corresponding events. The event is sent as a numeric code. Therefore, you can use a switch to select and process the event you are interested in. When parsing an element, call parser. nextText () to obtain the value of the next Text element.

2. Features

(1) Simple structure: an interface, an exception, and a factory constitute a Pull parser.

(2) ease of use: the Pull parser has only one important method, next (), which is used to retrieve the next event. There are only five events.

Ø start document;

Ø START_TAG;

Ø TEXT;

Ø END_TAG;

Ø END_DOCUMENT.

(3) versatility: common XML Parser and multiple implementations, with scalability.

(4) minimal requirement: it is designed to be compatible with JavaME and operate on small devices, and allows the creation of XMLPULL parser that occupies very small memory.

3. Working Principle

The method for parsing XML content is similar to that of SAX, which also includes the Start Element and end element event. You can use parser. next () to enter the next element and trigger the corresponding event. However, the difference between them is that the event-driven method of SAX is the callback method. You need to provide the callback method, and then automatically call the corresponding method within SAX. The Pull parser does not require a trigger method. Because the event triggered by it is not a method, but a number. It is up to the programmer to decide whether to handle the triggered event.


Here, the reader should understand why the Pull parser is integrated into Android. The Pull parser can also be used in non-Android projects such as JavaEE. It is not necessarily limited to Android development. Let's take an example to understand the Pull parsing process.

Public static List <Person> getPersons (InputStream inStream) throws Exception {Person person Person = null; List <Person> persons = null; XmlPullParser pullParser = Xml. newPullParser (); pullParser. setInput (inStream, "UTF-8"); int event = pullParser. getEventType (); // trigger the first event while (event! = XmlPullParser. END_DOCUMENT) {switch (event) {case XmlPullParser. START_DOCUMENT: persons = new ArrayList <Person> (); break; case XmlPullParser. START_TAG: if ("person ". equals (pullParser. getName () {int id = new Integer (pullParser. getAttributeValue (0); person = new Person (); person. setId (id);} if (person! = Null) {if ("name ". equals (pullParser. getName () {person. setName (pullParser. nextText ();} if ("age ". equals (pullParser. getName () {person. setAge (new Short (pullParser. nextText () ;}} break; case XmlPullParser. END_TAG: if ("person ". equals (pullParser. getName () {persons. add (person); person = null;} break;} event = pullParser. next ();} return persons ;}


Code Description:

1)IntEvent = pullParser. getEventType (); is the first event of the Pull parser. The reader can see that the return value of this method is of the int type, which is a number returned by the Pull parser mentioned above, similar to a signal. So what do these signals mean? The Pull parser has defined these five constants, and only these five constants are available for events, as shown below:

• XmlPullParser. START_DOCUMENT (start parsing, only once );

• XmlPullParser. START_TAG (Start Element );

• XmlPullParser. TEXT (parsing TEXT );

• XmlPullParser END_TAG (End Element );

• XmlPullParser END_DOCUMENT (end parsing, only once ).

2) "parser. getEventType ()" triggers the first event, starting with parsing the document according to the XML syntax. So how to trigger the next event? The most important method to use Parser is:

Parser. next ();

Note: This method has a returned value. When the Pull triggers an event, it also obtains the "signal" of the event ". Switch through the obtained signal.

3) "parsergetAttribiiteValue ()" to obtain the value of the corresponding attribute. It can be indexed either through an attribute index or through a namespace or an attribute name.

Ii. Use PULL to generate XML
public static void save(List<Person> persons, OutputStream outStream) throws Exception{    XmlSerializer serializer = Xml.newSerializer();    serializer.setOutput(outStream, "UTF-8");    serializer.startDocument("UTF-8", true);    serializer.startTag(null, "persons");    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();    outStream.flush();    outStream.close();}

Note:

(1) "XmlSerializCTserializer = Xml. newSerializer ()" defines an interface to serialize XML Information. What is serialization? It is also called object serialization. It not only saves objects in the memory, but also enables us to transmit objects through the network in binary mode, objects can be passed like basic data. Then, you can re-construct an object with the same status as the original object from these consecutive bytes through deserialization.

(2) define a method. The first parameter is the content of the XML file to be generated, and the second parameter is a writer. The Write interface is more flexible than the output stream. It can be output to more media, such as hard disk, memory, and network. "New" is a persistent XML object. Here, we should understand why persistence is required. To put it bluntly, writing data to the hard disk is a kind of action.

Serializer. setOutput (writer );

Set the output direction. It receives two types of output, namely the output stream and writer. This uses the writer introduced to the reader just now.

(3) The tags in XML are paired with each other. They have a start and end. Therefore, when writing a satrtTag (), I am used to writing the corresponding endTag (). In this way, the XML structure cannot be mistakenly generated when the structure is complex.

Method Description: The first batch is the XML namespace, the second is the tag name, And the endTag () is the same.

3. Application Example:

Android development parses XML and achieves three-level linkage

 


How to parse xml data retrieved from the background by android Developers

Android-three steps for parsing XML data

The specific steps for DOM parsing are as follows:
1. Use DocumentBuilderFactory to create a DocumentBuilderFactory instance
2. Use DocumentBuilderFactory to create DocumentBuilder.
3. Load the XML Document ),
4. Obtain the root node (Element) of the document ),
5. Then, obtain the list (NodeList) of all child nodes in the root node ),
6. Then, obtain the nodes to be read from the subnode list.

The specific processing steps for parsing using SAX are as follows:
1. Create a SAXParserFactory object
2. According to the SAXParserFactory. newSAXParser () method, a SAXParser parser is returned.
3. Get the event source object XMLReader Based on the SAXParser parser
4. instantiate a DefaultHandler object
5. Connect the event source object XMLReader to the event processing class DefaultHandler.
6. Call the parse method of XMLReader to obtain xml data from the input source.
7. Return the data set we need through DefaultHandler.

Basic PULL parsing method:
1: When you navigate to XmlPullParser. START_DOCUMENT, you do not need to process it. Of course, you can instantiate a collection object.
2: When you navigate to XmlPullParser. START_TAG, you can determine whether it is a river tag. If yes, the river object is instantiated and the getAttributeValue method is called to obtain the attribute values in the tag.
3: When you navigate to another label, such as Introduction, you can determine whether the river object is empty. If not, the content in Introduction is retrieved. The nextText method is used to obtain the content of the text node.
4: it will certainly navigate to XmlPullParser. END_TAG. It will end at the beginning. Here we need to determine whether the river end label is used. If yes, the river object is saved in the list set and the river object is set to null.

Comparison and summary of several parsing technologies:
For Android mobile devices, because the device resources are precious and the memory is limited, we need to select the appropriate technology to parse XML, which is conducive to improving the access speed.
1. When processing XML files, DOM parses the XML files into a tree structure and puts them in the memory for processing. When the XML file is small, we can select DOM because it is simple and intuitive. Www.2cto.com
2. SAX uses an event as the parsing XML file mode. It converts an XML file into a series of events, which are determined by different event processors. When the XML file is large, it is reasonable to select the SAX technology. Although the amount of code is large, it does not need to load all XML files into the memory. This is more effective for limited Android memory, and Android provides a traditional method of using SAX and a convenient SAX package.
3. XML pull parsing does not end listening elements like SAX parsing, but completes most of the processing at the beginning. This facilitates reading XML files early and greatly reduces the parsing time. This optimization is especially important for mobile devices with relatively high connection speeds. The XML Pull parser is more effective when the XML document is large but only a part of the document is required.

.. For details, you can view the relevant information .... Remaining full text>

In android, pull is used to parse xml data on the server. What is the xml data format required for pull parsing?

XmlPullParser parser = Xml. newPullParser ();
Parser. setInput (is, "UTF-8 ");
Int eventType = parser. getEventType ();
While (eventType! = XmlPullParser. END_DOCUMENT ){
Switch (eventType ){
Case XmlPullParser. START_DOCUMENT:

Break;
Case XmlPullParser. START_TAG:
If (parser. getName (). equals ("city ")){
// ---- City ---
} Else if (parser. getName (). equals ("id ")){
EventType = parser. next ();
// Parser. getText () is the id value.
System. out. println ("id =" + parser. getText ());
} Else if (parser. getName (). equals ("range ")){
EventType = parser. next ();
// Parser. getText () is the range value.
} Else if (parser. getName (). equals ("title ")){
EventType = parser. next ();
// Parser. getText () is the title value.
} Else if (parser. getName (). equals ("index ")){
EventType = parser. next ();
// Parser. getText () is the index value.
}
Break;
Case XmlPullParser. END_TAG:
If (parser. getName (). equals ("city ")){
}
Break;
}
EventType = parser. next ();
}
It is best to create a new class City
 

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.