Android USES PULL to parse XML files
- 2020-05-07 20:26:06
- OfStack
1. Basic introduction to
xmlpull parsing xml is highly recommended in Android.
xmlpull is available not only on Android but also on javase, but in the javase environment you need to get the class libraries on which xmlpull depends, kxml2-2.3.0.jar, xmlpull_1_1_3_4c.jar.
jar package download url
http://www.xmlpull.org/
http://kxml.sourceforge.net/
2. Example
A 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 closing tag read to xml returns the number 3 END_TAG
Text read to xml returns the number 4 TEXT
xmlpull parsing xml is highly recommended in Android.
xmlpull is available not only on Android but also on javase, but in the javase environment you need to get the class libraries on which xmlpull depends, kxml2-2.3.0.jar, xmlpull_1_1_3_4c.jar.
jar package download url
http://www.xmlpull.org/
http://kxml.sourceforge.net/
2. Example
A 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 closing tag read to xml returns the number 3 END_TAG
Text read to xml returns the number 4 TEXT
<?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>
public class PersonService
{
/**
* from XML The data is read from the file
*
* @param xml XML File input stream
*/
public List<Person> getPeople(InputStream xml) throws Exception
{
List<Person> lst = null;
Person person = null;
// To obtain pull Parser factory
XmlPullParserFactory pullParserFactory = XmlPullParserFactory.newInstance();
// To obtain XmlPullParser An instance of the
XmlPullParser pullParser = pullParserFactory.newPullParser();
// Set what needs to be resolved XML data
pullParser.setInput(xml, "UTF-8");
// In event
int event = pullParser.getEventType();
// If to resolve to the end
while (event != XmlPullParser.END_DOCUMENT) // End of the document
{
// The name of the node
String nodeName = pullParser.getName();
switch (event)
{
case XmlPullParser.START_DOCUMENT: // The beginning of the document
lst = new ArrayList<Person>();
break;
case XmlPullParser.START_TAG: // Tags 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: // End of the label
if ("person".equals(nodeName))
{
lst.add(person);
person = null;
}
break;
}
event = pullParser.next(); // Under the 1 A label
}
return lst;
}
}