XmlPullParser preferred way of getting child nodes?

帅比萌擦擦* 提交于 2019-12-24 03:44:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!