first, the basic introduction
Android is highly recommended for parsing XML in Xmlpull mode.
Xmlpull not only can be used on Android as well as Javase, but in javase environments it is necessary to get the Xmlpull-dependent class library, Kxml2-2.3.0.jar,xmlpull_1_1_3_4c.jar.
Jar Package Download URL
http://www.xmlpull.org/
http://kxml.sourceforge.net/
Second, examples
The declaration read to XML returns the number 0 start_document;
The end of reading to XML returns the number 1 end_document;
The start tag read to XML returns the number 2 Start_tag
The end tag read to XML returns the number 3 End_tag
Text read to XML returns the number 4 text
Copy Code code 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 Code code as follows:
public class Personservice
{
/**
* reading 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;
Get Pull Parser Factory
Xmlpullparserfactory pullparserfactory = Xmlpullparserfactory.newinstance ();
Get an instance of Xmlpullparser
Xmlpullparser Pullparser = Pullparserfactory.newpullparser ();
To set the XML data that needs to be resolved
Pullparser.setinput (XML, "UTF-8");
Get events
int event = Pullparser.geteventtype ();
If you are parsing to the end
while (event!= xmlpullparser.end_document)//End of document
{
Node name
String nodename = Pullparser.getname ();
Switch (event)
{
Case Xmlpullparser.start_document://Document Start
LST = new arraylist<person> ();
Break
Case XMLPULLPARSER.START_TAG://Label 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 label
}
return LST;
}
}