2011-06-03 83 views
0

我下RES/XML/hi.xml xml文件,当我使用下面的代码读取仅id元素,但我想读取XML标记不id值的内容Android的XML阅读

while (eventType != XmlPullParser.END_DOCUMENT) //Keep going until end of xml document 
{ 
    if (eventType == XmlPullParser.START_DOCUMENT) 
    { 
    Log.d("abhayxxxxx", myxml.getName() + "start document reading"); 
    //Start of XML, can check this with myxml.getName() in Log, see if your xml has read successfully 
    } 
    else if (eventType == XmlPullParser.START_TAG) 
    { 
    NodeValue = myxml.getName(); 
    Log.d("abhayxxxx", NodeValue + " node "); 
    //Start of a Node 
    if (NodeValue.equalsIgnoreCase("author")) 
    { 
     Log.d("abhayxxxx", "Reading data" + myxml.getAttributeValue(0)); 
    } 
    } 
    else if (eventType == XmlPullParser.END_TAG) 
    { 
    //End of document 
    } 
    else if (eventType == XmlPullParser.TEXT) 
    { 
    //Any XML text 
    } 

    try 
    { 
    eventType = myxml.next(); 
    } 
    catch (XmlPullParserException e) 
    { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
    } 
    catch (IOException e) 
    { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
    } 
} 

这里是xml文件的coontent

<?xml version="1.0"?> 
<catalog> 
    <book code="bk101"> 
     <author id="Gambardella, Matthew">content</author> 
    </book> 
    <book code="bk102"> 
     <author id="Ralls, Kim">content</author> 
    </book> 
</catalog> 

感谢

+0

我没有答案,因为我从来没有在android上使用XML解析器。尝试使用JSON。在基于java的应用程序中使用起来要容易得多。它还具有更小,更易于阅读的益处。 – Nallath 2011-06-03 11:59:40

+0

感谢您的建议:) – 2011-06-03 12:02:10

+0

除非您在限制其禁止使用的情况下工作,否则我强烈建议您使用XML序列化/反序列化API,如XStream http://xstream.codehaus.org,而不是手动解析XML。 – 2011-06-03 12:31:25

回答

1

我认为问题是在这里getAttributeValue()函数:

if (NodeValue.equalsIgnoreCase("author")) 
     { 

       Log.d("abhayxxxx","Reading data" + myxml.getAttributeValue(0)); 

     } 

当您使用getAttributeValue(0)时,它将返回标记的属性值,而不是您想要的节点值。获取节点值使用nextText()函数。

+0

其工作非常感谢:) – 2011-06-03 12:32:52

+0

我是新的堆栈溢出我不能投票,直到我有15名声望:( – 2011-06-03 12:46:00