I. Basic Introduction
The xmlpull method is strongly recommended for parsing xml in Android.
Xmlpull is also applicable to javase not only on Android, but in the javase environment, you need to obtain the class library, kxml2-2.3.0.jar, xmlpull_1_1_3_4c.jar that xmlpull depends on.
Jar package download URL
Http://www.xmlpull.org/
Http://kxml.sourceforge.net/
Ii. Example
Returns the number 0 START_DOCUMENT;
The number 1 END_DOCUMENT is returned when the end of the read to xml;
Returns the number 2 START_TAG.
Returns the number 3 END_TAG.
The TEXT read to xml returns the number 4 TEXT
Copy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<People>
<Person id = "001">
<Name> XY1 </name>
<Age> 22 </age>
</Person>
<Person id = "002">
<Name> XY2 </name>
<Age> 22 </age>
</Person>
</People>
Copy codeThe Code is as follows: public class PersonService
{
/**
* Read data from an XML file
*
* @ Param xml XML file input stream
*/
Public List <Person> getPeople (InputStream xml) throws Exception
{
List <Person> lst = null;
Person person = null;
// Obtain the pull parser factory
XmlPullParserFactory pullParserFactory = XmlPullParserFactory. newInstance ();
// Obtain the XmlPullParser instance
XmlPullParser pullParser = pullParserFactory. newPullParser ();
// Set the XML data to be parsed
PullParser. setInput (xml, "UTF-8 ");
// Obtain the event
Int event = pullParser. getEventType ();
// If it is resolved to the end
While (event! = XmlPullParser. END_DOCUMENT) // end of the document
{
// Node name
String nodeName = pullParser. getName ();
Switch (event)
{
Case XmlPullParser. START_DOCUMENT: // start of the document
Lst = new ArrayList <Person> ();
Break;
Case XmlPullParser. START_TAG: // tag start
If ("person". equals (nodeName ))
{
String id = pullParser. getAttributeValue (0 );
Person = new Person ();
Person. setId (id );
}
If ("name". equals (nodeName ))
{
String name = pullParser. nextText ();
Person. setName (name );
}
If ("age". equals (nodeName ))
{
Int age = Integer. valueOf (pullParser. nextText ());
Person. setAge (age );
}
Break;
Case XmlPullParser. END_TAG: // tag end
If ("person". equals (nodeName ))
{
Lst. add (person );
Person = null;
}
Break;
}
Event = pullParser. next (); // next tag
}
Return lst;
}
}