我正在解析这个 xml。我想从属性中获取所有值,但经过大量搜索后,我只能获取第一个项目值。谁能告诉我如何从所有项目中获取所有 id。我也粘贴了我的代码
XML:
<query>
<item id='9173' name='A'/>
<item id='9174' name='B'/>
<item id='9175' name='C'/>
<item id='9176' name='D'/>
<item id='9174' name='E'/>
</query>
代码:
boolean done = false;
while (!done) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG) {
}
else if (eventType == XmlPullParser.END_TAG) {
Map<String,String> attributes = getAttributes(parser);
if (parser.getName().equals("query")) {
done = true;
}
}
}
private Map<String,String> getAttributes(XmlPullParser parser) throws Exception { Map<String,String> attrs=null;
int acount=parser.getAttributeCount();
if(acount != -1) {
Log.d(MY_DEBUG_TAG,"Attributes for ["+parser.getName()+"]");
attrs = new HashMap<String,String>(acount);
for(int x=0;x<acount;x++) {
Log.d(MY_DEBUG_TAG,"\t["+parser.getAttributeName(x)+"]=" +
"["+parser.getAttributeValue(x)+"]");
attrs.put(parser.getAttributeName(x), parser.getAttributeValue(x));
}
}
else {
throw new Exception("Required entity attributes missing");
}
return attrs;
}
最佳答案
在getAttributes
中,您调用getAttributeCount
,according to the doc (强调我的):
Returns the number of attributes of the current start tag, or -1 if the current event type is not START_TAG
由于您的 if 条件恰好在确保您位于 END_TAG 之前,因此这是行不通的,并且您的 getAttributes
调用应始终引发异常。
您可能应该像这样重写它(免责声明:未经测试):
boolean done = false;
while (!done) {
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("query")) {
done = true;
} else if (parser.getName().equals("item")) {
Map<String,String> attributes = getAttributes(parser);
}
}
else if (eventType == XmlPullParser.END_TAG) {
}
int eventType = parser.next();
}
关于java - android中解析xml属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25989413/