问题描述
获取XML字符串的子节点的首选方法是什么?似乎缺少在Android中使用XmlPullParser进行解析的良好示例.例如,如果我想解析这个:
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?
推荐答案
一种处理XML文本的更好方法就是在这里进行解释:
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()不会生成异常,因为您位于XmlPullParser.TEXT区域内(因此可以确定是否有Text).
getText() wont generate Exceptions because you are inside an XmlPullParser.TEXT zone (so it is sure Text is there).
希望有帮助!
这篇关于XmlPullParser获取子节点的首选方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!