【问题标题】:C# XDocument Read all Nodes from XML-FileC# XDocument 从 XML 文件中读取所有节点
【发布时间】: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。你真正想要什么作为这里的输出?你能举个例子吗?

标签: c# xml


【解决方案1】:

您需要使用Value 属性,即sb.Append(xe.Value)

【讨论】:

    【解决方案2】:

    试试下面的代码。 Comment的innertag不需要尖括号,所以去掉。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    using System.Xml;
    using System.Xml.Linq;
    
    
    namespace ConsoleApplication49
    {
    
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XDocument doc = XDocument.Load(FILENAME);
                var results = doc.Descendants("Item").Select(x => new {
                    name = (string)x.Element("Name"),
                    count = (int)x.Element("Count"),
                    price = (decimal)x.Element("Price"),
                    comment = (string)x.Element("Comment"),
                    artist = (string)x.Element("Artist"),
                    publisher = (string)x.Element("Publisher"),
                    genre = (string)x.Element("Genre"),
                    year = (int)x.Element("Year"),
                    productID = (string)x.Element("ProductID")
                }).ToList();
    
            }
        }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 2021-02-24
      相关资源
      最近更新 更多