XML to be parsed:
<? XML version = "1.0" encoding = "UTF-8"?>
<Persons>
<Person id = "23">
<Name> instructor Zhang </Name>
<Age> 21 </age>
<Persion>
<Person id = "20">
<Name> instructor Li </Name>
<Age> 25 </age>
<Persion>
</Persons>
The jar package where the response needs to be downloaded: http://www.xmlpull.org/v1/download/unpacked/doc/
Main java files:
// Create a factory for XML Parsing
Xmlpullparserfactory factory = xmlpullparserfactory. newinstance ();
// Obtain the reference of the XML parsing class
Xmlpullparser parser = factory. newpullparser ();
// Input the XML data to be parsed as a stream
Parser. setinput (Java. Io. Reader in );
// Obtain the Event Type
Int eventtype = parser. geteventtype ();
// Determine whether the end of the document is reached
While (eventtype! = Xmlpullparser. end_document ){
Switch (eventtype ){
// Start reading the document
Case xmlpullparser. start_document:
Break;
// Encounter tag Elements
Case xmlpullparser. start_tag:
If ("person". Equals (parser. getname ())){
// Retrieve the attribute value. 0 indicates 0th attributes.
Int id = integer. parseint (parser. getattributevalue (0 ));
} Else if ("name". Equals (parser. getname ())){
// Obtain the content of the node
String name = parser. nettext ();
} Else if ("Age". Equals (parser. getname ())){
// Obtain the content of the node
String age = parser. nettext ();
}
Break;
// Tag ends
Case xmlpullparser. end_tag:
If ("person". Equals (parser. getname ())){
// Initialization can be performed here
}
Break;
}
// Loop
Eventtype = parser. Next ();
}