Search code examples
androidxmlxmlpullparser

Parsing complex XML using XmlPullParser


I'm facing the problem of parsing xml using XmlPullParser. Everithing works fine except this problmatic part:

<Device> 

    <Description>
            Tracker, type CONNECT
            <Firmware>0240</Firmware>
    </Description>

    <Settings>
    ...
    </Settings>

    <Variables>
    ...
    </Variables>
</Device>

I need to parse both DESCRIPTION and FIRMWARE. But I can't read properly that description text because of such tags weird structure.

What I've tried (following this guide):

private Device parseDevice(XmlPullParser parser) throws XmlPullParserException, IOException {
    Device device = new Device();

    parser.require(XmlPullParser.START_TAG, ns, DEVICE);
    //device.setDescription(readDeviceDescription(parser)); <---tried to parse from here
    device.setName(readDeviceName(parser));

    while (parser.next() != XmlPullParser.END_TAG) {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            continue;
        }
        String name = parser.getName();

        // Starts by looking for the entry tag
        switch (name) {
            case DESCRIPTION:
                //  device.setDescription(readDeviceDescription(parser)); <---and from here
                device.setFirmware(readDescription(parser, device)); //<-- and inside this method
                break;

            case VARIABLES:
                device.setGroups(readGroups(parser));
                break;

            default:
                skip(parser);
                break;
        }
    }
    return device;
}

readDeviceDesscription() method (maybe problem lies here):

private String readDeviceDescription(XmlPullParser parser) throws XmlPullParserException, IOException {
    String result = "";
    if (parser.next() == XmlPullParser.TEXT) {
        result = parser.getText();
        parser.next();
    }
    return result;
}

But any my attempt was ending with returning null either to Firmware or to Description.

Please help. Appreciate any hint.


Solution

  • You should do:

    private String readDeviceDescription(XmlPullParser parser) throws XmlPullParserException, IOException {
        String result = parser.getText();
        return result;
    }
    

    Since you are already positioned at Description start_tag getText call will return the text inside Description tag.

    To get the Firmware tag text you should do:

    if(parser.getEventType() == XmlPullParser.START_TAG && parser.getName().compareTo("Firmware")==0)
        String firmwareText = parser.getText();
    

    Also take a look at this its a good example of a clean XmlPullParser implementation.

    Hope this helps.