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

时间:2022-08-16 19:33:22

Here's my code:

这是我的代码:

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());
}

The XML:

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>

The output:

输出:

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

Notice how there are lines File name10101010. I cannot figure out how to get the correct file name: Sea Wallpaper.jpg. It's giving me the image id but not the file name.

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

1 个解决方案

#1


1  

You dont need to perform 2 XPath queries against your xml document, one will suffice. This code should demonstrate how to get bothe the id attribute and the inner text of the node:

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

Live example: http://rextester.com/rundotnet?code=THABU16531

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

#1


1  

You dont need to perform 2 XPath queries against your xml document, one will suffice. This code should demonstrate how to get bothe the id attribute and the inner text of the node:

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

Live example: http://rextester.com/rundotnet?code=THABU16531

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