I am using the XmlPullParser to pull data from an XML document. My XML document is structured like this:
<creature id="1">
<name>CreatureName</name>
<type>CreatureType</type>
<size>CreatureSize</size>
</creature>
<creature id="2">
<name>CreatureName</name>
<type>CreatureType</type>
<size>CreatureSize</size>
</creature>
<creature id="3">
<name>CreatureName</name>
<type>CreatureType</type>
<size>CreatureSize</size>
</creature>
My code is currently working if I only have one creature in my XML file.
I’m looking for a way to chose the creature based on the creature ID. For example, if the ID was 2, then the XMLPullParser would only parse the XML under creature ID=”2″.
Here is my code so far:
xpp.next();
String elName = "";
int encounterId = 0;
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
if(eventType == XmlPullParser.START_DOCUMENT)
{
System.out.println("START_DOCUMENT "+xpp.getName());
}
else if(eventType == XmlPullParser.START_TAG)
{
if(encounterId >= 0) {
if(xpp.getName().equalsIgnoreCase("creature")) {
System.out.println("inside while loop --- "+xpp.getName());
try {
encounterId = Integer.parseInt(xpp.getAttributeValue(0));
System.out.println("attribute value = " + encounterId);
} catch (NumberFormatException e) {
Log.e("attribute value error", e.getMessage());
}
//DETERMINE ELEMENT NAME
} else if(xpp.getName().equalsIgnoreCase("name")) {
System.out.println("inside while loop --- "+xpp.getName());
elName = "name";
} else if(xpp.getName().equalsIgnoreCase("type")) {
elName = xpp.getName();
elName = "type";
} else if(xpp.getName().equalsIgnoreCase("size")) {
elName = xpp.getName();
elname = "size";
}
} else if(eventType == XmlPullParser.END_TAG) {
System.out.println("End tag "+xpp.getName());
} else if(eventType == XmlPullParser.TEXT) {
//COLLECT DATA
if(elName.equalsIgnoreCase("name")) {
this.name = xpp.getText();
} else if(elName.equalsIgnoreCase("type")) {
this.race = xpp.getText();
} else if(elName.equalsIgnoreCase("size")) {
this.gender = xpp.getText();
}
eventType = xpp.next();
}
Thanks!
You should use XPath for it