【问题标题】:parse xml attributes in android在android中解析xml属性
【发布时间】:2014-09-23 07:31:45
【问题描述】:

我正在解析这个 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;
}

【问题讨论】:

  • 一些缩进和格式化有助于提高可读性!
  • 谢谢。我在粘贴代码时遇到问题。第一次发布
  • 据我所知,它应该可以工作,你怎么知道它不工作,你没有对你检索到的属性做任何事情?
  • Log.d(MY_DEBUG_TAG,"\t["+parser.getAttributeName(x)+"]=" + "["+parser.getAttributeValue(x)+"]"); ......它只打印一次这个日志。它应该打印 6 次
  • stackoverflow.com/questions/20216243/… 终于在这里找到答案了..

标签: java android


【解决方案1】:

在getAttributes 中,您调用getAttributeCount 其中according to the doc(强调我的):

返回当前开始标签的属性个数,如果当前事件类型不是START_TAG则返回-1

由于您的 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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-06
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多