XmlPullParser getAttributeCount() is always -1

52 views Asked by At

I'm trying to parse the following XML stuff.xml to extract the attributes within each block:

<?xml version="1.0" encoding="utf-8"?>
<MyGroup xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto">

    <CompoundSwitch
        android:id="@+id/testing"
        custom:switch_label_tag="label_testing"
        custom:switch_label_text="testing"
        custom:switch_indented="false"
        android:visibility="visible" />

    <CompoundEditText
        android:id="@+id/text_input"
        custom:edit_text_label_tag="label_text"
        custom:edit_text_label_text="text"
        custom:edit_text_label_text_2="postfix"
        custom:edit_text_indented="false"
        android:inputType="text|textMultiLine"
        android:visibility="visible" />

</MyGroup>

The code I'm using is:

XmlPullParser parser = getResources().getXml(R.xml.stuff);

while (true) {
    try {
        parser.next();
        parser.nextTag();
        String name = parser.getName();
        Log.d(TAG, "name: " + name);
        if (!name.equals("MyGroup")) {
            int count = parser.getAttributeCount();
            Log.d(TAG, "count: " + count);
            if (count != -1) {
                int eventType = parser.getEventType();
                Log.d(TAG, "eventType: " + eventType);
                AttributeSet attr = Xml.asAttributeSet(parser);
                Log.d(TAG, "attr: " + attr.getAttributeName(0));
                // ... do something with AttributeSet here...
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        break;
    }
}

But I'm finding that that count is always -1 so I never get to read the AttributeSet for each block.

What am I doing wrong?

1

There are 1 answers

0
AIMIN PAN On

attributeCount should be called only when event type is START_TAG.

Here is my code to do xml pull parser:

    var eventType = _xml.eventType
    while (eventType != XmlPullParser.END_DOCUMENT) {
        try {
            when (eventType) {
                XmlPullParser.START_TAG -> {
                   val cnt = _xml.attributeCount
                   .......
                }