问题
What would be the preferred way of getting the child nodes of a XML string? There seems to be a lack of good examples of parsing with the XmlPullParser in android. For example if I would want to parse this:
<Point>
<Id>81216</Id>
<Name>Lund C</Name>
</Point>
I came up with a way that does the job:
List<Point> points = new ArrayList<Point>();
String id = null
name = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("Id")) {
try {
id = xpp.nextText();
} catch (Exception e) {
e.printStackTrace();
}
}
else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("Name")) {
try {
name = xpp.nextText();
} catch (Exception e) {
e.printStackTrace();
}
else if(eventType == XmlPullParser.END_TAG && xpp.getName().equals("Point")) {
Point point = new Point(id, name);
points.add(point);
}
try {
eventType = xpp.next();
} catch (exception e) {
e.printStackTrace();
}
}
for (Point p : points) {
tv.append(p.getId() + " | " + p.getName() + "\n");
}
But it seems really ugly. Is there a better way of doing this?
回答1:
A better way to deal with texts in XML, in my opinion, would be like it is explained here:
http://androidcookbook.com/Recipe.seam?recipeId=2217
getText() wont generate Exceptions because you are inside an XmlPullParser.TEXT zone (so it is sure Text is there).
Hope it helps!
来源:https://stackoverflow.com/questions/11588439/xmlpullparser-preferred-way-of-getting-child-nodes