XmlPullParser getAttributeCount() is always -1



我正在尝试解析以下XMLstuff.xml以提取每个块中的属性:

<?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>

我使用的代码是:

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;
}
}

但我发现count总是-1,所以我永远无法读取每个块的AttributeSet

我做错了什么?

只有当事件类型为START_TAG时,才应调用attributeCount。

这是我的代码做xml拉解析器:

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

最新更新