获取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");
}


但这看起来真的很丑。有更好的方法吗?

最佳答案

我认为,一种更好的处理XML文本的方法就像在这里进行解释:

http://androidcookbook.com/Recipe.seam?recipeId=2217

getText()不会生成异常,因为您位于XmlPullParser.TEXT区域内(因此可以确定Text在那里)。

希望能帮助到你!

07-24 09:50
查看更多