2

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?

  • other then the awful use of Exception.printStackTrace(), that's pretty much spot on. – jtahlborn Jul 21 '12 at 00:28
  • hehe, what's awful with it? Eclipse forces me to write it out? :) – Christer William Persson Jul 21 '12 at 00:32
  • 1
    because if you get an exception (which most likely means the xml parsing failed), you will 1. most likely never see it as the console will probably be hidden and 2. continue happily with your code as if nothing happened (will cause more problems later in the code) . eclipse doesn't force you to write it, eclipse forces you to _deal_ with it. adding `e.printStackTrace()` is _never_ dealing with it. – jtahlborn Jul 21 '12 at 00:37
  • Makes sense. Thanks :) Didn't deal with it specifically since it was out of the scope of the question also – Christer William Persson Jul 21 '12 at 00:45
  • in that case it it would be better to omit it. – jtahlborn Jul 21 '12 at 00:47

1 Answers1

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!

charlypu
  • 158
  • 8