【发布时间】:2017-08-29 10:21:40
【问题描述】:
我有一个这样的 XML 文件:
<Inventory>
<Item>
<Name>Super Mario Bros</Name>
<Count>14</Count>
<Price>29,99</Price>
<Comment><No Comments on this Product></Comment>
<Artist>N/A</Artist>
<Publisher>Nintendo</Publisher>
<Genre>Video Games</Genre>
<Year>1985</Year>
<ProductID>001</ProductID>
</Item>
<Item>
<Name>The Legend of Zelda</Name>
<Count>12</Count>
<Price>34,99</Price>
<Comment><No Comments on this Product></Comment>
<Artist>N/A</Artist>
<Publisher>Nintendo</Publisher>
<Genre>Video Games</Genre>
<Year>1986</Year>
<ProductID>002</ProductID>
</Item>
<Item>
<Name>Street Fighter</Name>
<Count>82</Count>
<Price>19,99</Price>
<Comment><No Comments on this Product></Comment>
<Artist>N/A</Artist>
<Publisher>Nintendo</Publisher>
<Genre>Video Games</Genre>
<Year>1987</Year>
<ProductID>003</ProductID>
</Item>
</Inventory>
(还有更多的项目,但除了值之外,它们都是一样的。)
现在我想遍历每个 Item 并从每个节点中提取每个值。到目前为止,这是我尝试过的:
var xDocument = XDocument.Load(FilePath_CSVToXML);
string xml = xDocument.ToString();
StringBuilder sb = new StringBuilder();
foreach (XElement xe in xDocument.Descendants("Inventory")) {
sb.Append(xe);
}
Console.WriteLine(sb.ToString());
Console.ReadLine();
上面的代码正确地显示了 XML 文件,但它保留了节点。 (名称、数量、价格等)我只想要值。
【问题讨论】:
-
您的查询不会读取所有节点,它会读取单个元素:
Inventory。你真正想要什么作为这里的输出?你能举个例子吗?