无法从XML文件中获取正确的数据

时间:2011-10-07 07:18:48

标签: c# xml

这是我的代码:

XmlNodeList otherImageId =
    document.DocumentElement
            .SelectNodes("/OHManager/config/customimage/image/@id");

XmlNodeList otherImage =
    document.DocumentElement
            .SelectNodes("/OHManager/config/customimage/image");

for (int i = 0; i < 5; i++)
{
    Console.WriteLine("Image Id" + otherImageId[i].InnerText.ToString());
    Console.WriteLine("File name" + otherImage[i].InnerText.ToString());
}

XML:

<OHManager>
  <config type="image">
    <customimage no="5">
      <image id="1">Sea Wallpaper.jpg</image>
      <image id="2">Sea Wallpaper.jpg</image>
      <image id="3">Sea Wallpaper.jpg</image>
      <image id="4">Sea Wallpaper.jpg</image>
      <image id="5">Sea Wallpaper.jpg</image>
    </customimage>
  </config>
</OHManager>

输出:

Image Id1
File name10101010
Image Id2
File name10101010
Image Id3
File name10101010
Image Id4
File name10101010
Image Id5 

注意行File name10101010是怎样的。我无法弄清楚如何获得正确的文件名:Sea Wallpaper.jpg。它给了我图像ID但不是文件名。

1 个答案:

答案 0 :(得分:1)

您不需要对xml文档执行2次XPath查询,只需一次即可。此代码应演示如何获取id属性和节点的内部文本:

XmlNodeList list = document.DocumentElement
                        .SelectNodes("/OHManager/config/customimage/image");

foreach(XmlElement node in list)
{
    Console.WriteLine("Image Id: {0}, FileName: {1}",
               node.Attributes["id"].Value,
               node.Value);
}

实例:http://rextester.com/rundotnet?code=THABU16531