xmlxml-parsingxmlpullparser

XmlPullParser - How to skip to matching END_TAG?


<root>
    <element> <!-- When this is encountered... -->
        <element>text</element>
        <element>text</element>
        <element>
            <element>text</element>
        </element>
    </element> 
    <element> <!-- ...skip to here. -->
        <element>text</element>
        <element>text</element>
        <element>
            <element>text</element>
        </element>
    </element>
</root>

The inner tags may have the same name as the outer tag. In this case they are all called element.

Basically, if I am at any given START_TAG I want to skip to its corresponding END_TAG and continue parsing from the next START_TAG at the same depth.


Solution

  • Found a snippet on the Android developer website.

     private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            throw new IllegalStateException();
        }
        int depth = 1;
        while (depth != 0) {
            switch (parser.next()) {
            case XmlPullParser.END_TAG:
                depth--;
                break;
            case XmlPullParser.START_TAG:
                depth++;
                break;
            }
        }
     }