获取XML字符串的子节点的首选方法是什么?在android中似乎缺少使用XmlPullParser解析的好例子。例如,如果我想解析这个:
<Point>
<Id>81216</Id>
<Name>Lund C</Name>
</Point>
我提出了一种完成工作的方法:
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");
}
但它看起来真的很难看。有没有更好的方法呢?
答案 0 :(得分:1)
在我看来,更好的处理XML文本的方法就像在这里解释一样:
http://androidcookbook.com/Recipe.seam?recipeId=2217
getText()不会生成异常,因为您位于XmlPullParser.TEXT区域内(因此确保Text在那里)。
希望它有所帮助!