I am parsing this xml. I want to get all the values from attributes but after searching a lot I am only able to fetch the first item value. Can anybody let me know how can I get all the id from all the items. I have pasted my code also
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>
Code:
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;
}
In getAttributes
you call getAttributeCount
which, according to the doc (emphasis mine) :
Returns the number of attributes of the current start tag, or -1 if the current event type is not START_TAG
As your if condition juste before make sure that you are on a END_TAG, this cannot work and your getAttributes
call should always throw an exception.
You should probably rewrite it like this (disclaimer : not tested) :
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.