Android XML阅读

时间:2011-06-03 11:48:49

标签: android xml parsing

我在res / xml / hi.xml下有xml文件,当我使用下面的代码时它只读取id元素但我想读取xml标记的内容而不是id值

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>

由于

1 个答案:

答案 0 :(得分:1)

我认为问题在于getAttributeValue()函数:

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

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

        }

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