Android: Finding out the Tag scope with the help of XmlPullParser

46 views Asked by At

as the title states, with the following function, it's possibile to get the Tags of a XML file:

public static void parseXML(Context context) {
        XmlPullParserFactory parserFactory;
        try {
            parserFactory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = parserFactory.newPullParser();
            InputStream is = context.getAssets().open("example.xml");
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(is, null);

            processParsing(parser);

        } catch (XmlPullParserException e) {

        } catch (IOException e) {
        }
}

public static void processParsing(XmlPullParser parser) throws IOException, XmlPullParserException{
        int eventType = parser.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {
            String eltName = null;

            switch (eventType) {
                case XmlPullParser.START_TAG:
                    eltName = parser.getName();

                    System.out.println(eltName); //Delievers the TAG-Name
                    break;
            }

            eventType = parser.next();
        }
    }

XML:example.xml

<data>
    <daten>
        <id> 122 </id>
        <name>ExampleName</name>
        <wert>154</wert>
        <exmpl>dsadas</exmpl>
        <datei>
            <id> 10 </id>
            <name>ExampleName 2</name>
            <wert>122</wert>
            <exmpl>gdasdas</exmpl>
        </datei>
    </daten>
</data>

Issue: as you can see there are multiple tags of: id, name, wert, exmpl.

Question: How do i know when parsing, whether i am within as outer scope, or ?

1

There are 1 answers

0
ardget On

A simple way to achive that is composing absolute path by using a stack. Push element name on START_TAG and pop it on END_TAG. Joining all the strings in the stack, you can get absolute path of the element in the xml tree. e.g. "data/daten/id", "data/daten/datei/id" etc.

public static void processParsing(XmlPullParser parser) throws IOException, XmlPullParserException{
    int eventType = parser.getEventType();
    Stack<String> stack = new Stack<>();

    while (eventType != XmlPullParser.END_DOCUMENT) {
        String eltName = null;

        switch (eventType) {
            case XmlPullParser.START_TAG:
                eltName = parser.getName();
                stack.push(eltName);

                String absPath = TextUtils.join("/", stack);
                System.out.println(absPath);

               // System.out.println(eltName); //Delievers the TAG-Name
                break;
            case XmlPullParser.END_TAG:
                stack.pop();
                break;
        }

        eventType = parser.next();
    }
}