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

本文关键字:数据 获取 XML 文件 | 更新日期: 2023-09-27 18:10:34

我的代码:

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,而不是文件名

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

您不需要对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