I'm trying to pull information from a xml file and this is the code which I'm currently developing to make it work.
private void parseXML(XmlPullParser parser)
throws XmlPullParserException, IOException {
int eventType = parser.getEventType();
Map<String, Map<String, Double>> sports = new HashMap<String, Map<String, Double>>();
while (eventType != XmlPullParser.END_DOCUMENT) {
String name = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
String sportName = null;
boolean paid = false;
Map<String, Double> preset = null;
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
preset = new HashMap<String, Double>();
break;
case XmlPullParser.START_TAG:
name = parser.getName();
if (name.equals("sport")) {
sportName = parser.getAttributeValue(0);
paid = Boolean.parseBoolean(parser
.getAttributeValue(1));
} else if (name.equals("preset")) {
// TODO figure out how to loop this so it finished up the sport and then moves on to the next one
String presetName = parser
.getAttributeValue(0);
double value = Double.parseDouble(parser
.nextText());
preset.put(presetName, value);
parser.next();
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
}
sports.put(sportName, preset);
eventType = parser.next();
}
}
}
And this is the xml its pulling the information from
<?xml version="1.0" encoding="utf-8"?>
<sports>
<sport name="Baseball" paid="false">
<preset name="Pitching Mound">726.0</preset>
<preset name="Base Distance">1080.0</preset>
</sport>
<sport name="Basketball" paid="false">
<preset name="NBA Free Throw Line">181.08</preset>
<preset name="NBA 3pt Line">265.8</preset>
</sport>
<sport name="Cricket" paid="true">
<preset name="Cricket Pitch">2012.0</preset>
</sport>
</sports>
What the code essentially does is getting the sport name, whether it is a paid feature or not, and the presets I have defined for it. What I'm trying to do is make the part, where it adds a preset to the preset map, loop till the end of the sports presets. I'm not 100% comfortable with using the xml parses because I get confused with using it. I tried getting the attribute count when the code gets the name of the sport, and then looping it but it didnt work.
While the android docs saying its recommended to use XmlPullParser you can use parser of your choice.
To get attribute you can use
parser.getAttributeValue(null, "name")
coz you have<preset name="Pitching Mound">
. Name is the attribute.To get the text use
text
.There is a example in the docs. It has separate methods for each tag while the method is the same.
http://developer.android.com/training/basics/network-ops/xml.html
You can use the below for reference.
Log Output
Edit:
To get the attribute paid just add the below in
case XmlPullParser.START_TAG: