【问题标题】:Parsing XML and cast elements to a typed collection using LINQ, C#使用 LINQ、C# 解析 XML 并将元素转换为类型化集合
【发布时间】:2010-10-17 18:22:59
【问题描述】:

我有一个 XML 文档:

<statuses>
  <status>
  </status>
  <status>
  </status>
</statuses>

我已将其解析为 XDocument,并希望使用 LINQ 将元素选择到状态类的强类型集合中(所有状态元素都是简单类型,字符串或 int)。

有什么想法可以做到这一点吗?

谢谢!

【问题讨论】:

  • 您正在使用的 xml 的任何示例?

标签: c# .net xml linq collections


【解决方案1】:

使用XDocument,如下所示:

    class Status
    {
        public int Id { get; set; }
        public string Text { get; set; }
    }
    static void Main()
    {
        string xml = @"<xml>
<status id='1'><text>abcdef</text></status>
<status id='2'><text>ghijkl</text></status>
<status id='3'><text>mnopqr</text></status></xml>";
        XDocument doc = XDocument.Parse(xml);

        var list = (from el in doc.Root.Elements("status")
                   select new Status
                   {
                       Id = (int)el.Attribute("id"),
                       Text = (string)el.Element("text")
                   }).ToList();
    }

请注意,XmlSerializer 在这里也有可能 - 减少您需要编写和维护的代码量。

【讨论】:

  • 小建议编辑:使用'而不是"作为属性值意味着你不需要引用任何东西:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多