简体   繁体   English

解析android中的xml属性

[英]parse xml attributes in android

I am parsing this xml. 我正在解析此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. 有人可以让我知道如何从所有商品中获取所有ID。 I have pasted my code also 我也粘贴了我的代码

XML: 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) : getAttributes您调用getAttributeCount根据doc (强调我的观点):

Returns the number of attributes of the current start tag, or -1 if the current event type is not START_TAG 返回当前开始标记的属性数; 如果当前事件类型不是START_TAG返回-1。

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. 由于您之前的if条件只是确保您使用的是END_TAG,因此无法正常工作,并且getAttributes调用应始终引发异常。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM