简体   繁体   中英

How to parse XML string with XmlPullParser in Java?

I have this xml:

<xml><result>-1</result></xml>

and following java code:

public String findElement(String xml, String elem) {
    try {
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser xpp = factory.newPullParser();

        xpp.setInput( new StringReader (xml) );

        while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
            if (xpp.getName().equals(elem)) {
                return xpp.getText();
            }
            xpp.next();
        }
    } catch (XmlPullParserException | IOException e) {
        e.printStackTrace();
    }
    return null;
}

But xpp.getName() returns null instead of "result" . As result NullPointerException is throwed.

Where am I wrong?

Change your code like this.

        int eventType = xpp.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG) {
                if (xpp.getName().equals(elem)) {
                    eventType = xpp.next(); // advance to inner text
                    return xpp.getText();
                }
            }
            eventType = xpp.next();
        }

XmlPullParser doc

Of course you need to check some more conditions like what if there is no text or tag consist another nested tag...

public String findElement(String xml, String elem) {
    try {
      XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
      factory.setNamespaceAware(true);
      XmlPullParser xpp = factory.newPullParser();

      xpp.setInput(new StringReader(xml));
      while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {

        final int event = xpp.getEventType();
        if (event == XmlPullParser.START_TAG && xpp.getName().equals(elem)) {
          xpp.next();
          return xpp.getText();
        }
        xpp.next();

      }
    } catch (XmlPullParserException | IOException e) {
      e.printStackTrace();
    }
    return null;
  }

and this

        if (event == XmlPullParser.START_TAG && xpp.getName().equals(elem)) {
      xpp.next();
      if (xpp.getEventType() == XmlPullParser.TEXT) {
        return xpp.getText();
      }
    }else{
      xpp.next();
    }

would work for something nested like

"<xml><result><noway><result>-1</result></noway></result></xml>"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM