简体   繁体   English

使用LINQ,如何将分层XML加载到POCO中?

[英]Using LINQ, how do I load a hierarchical XML into a POCO?

I want to build a C# object from hierarchical XML data usinq LINQ. 我想从分层XML数据usinq LINQ构建C#对象。 I have loaded the XML as an XDocument (by reading the XML from a file into a string first). 我已经将XML加载为XDocument (首先将XML从文件中读取到字符串中)。 I need some guidance on how I should parse this. 我需要一些有关如何解析此内容的指导。

Example string read from XML file as 从XML文件读取的示例字符串

<?xml version="1.0" encoding="utf-8" ?>
<categories version="1.0">
  <category id="0" name="women" description="test">
    <category id="01" name="tops" description="test"></category>
    <category id="02" name="bottoms" description="test"></category>
    <category id="03" name="accessories" description="test"></category>
  </category>
  <category id="1" name="men" description="test">
    <category id="11" name="shirts" description="test"></category>
    <category id="12" name="trousers" description="test"></category>
    <category id="13" name="accessories" description="test"></category>
  </category>
  <category id="2" name="kids &amp; baby" description="test" />
  <category id="3" name="home &amp; living" description="test" />
</categories>

And I have such a POCO class: 我有这样的POCO课程:

[DataContract]
public class Category
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Description { get; set; }

    [DataMember]
    public List<Category> SubCategories { get; set; }
}

You have two options. 您有两个选择。

  1. Use .NET serialization, in which case you need to specify the XML mappings by decorating your POCO class with appropriate attributes (property name ⇄ XML element name). 使用.NET序列化,在这种情况下,您需要通过使用适当的属性(属性名称⇄XML元素名称)修饰POCO类来指定XML映射。

  2. Use LINQ to XML (like you want do). 使用LINQ to XML(就像您想要的那样)。 In that case, the code could look something like this: 在这种情况下,代码可能如下所示:

     var categories = x.Root.Elements().Select(e => new Category { Id = int.Parse(e.Attribute("id").Value), Name = e.Attribute("name").Value, Description = e.Attribute("description").Value, SubCategories = e.Elements().Select(e1 => new Category { Id = int.Parse(e1.Attribute("id").Value), Name = e1.Attribute("name").Value, Description = e1.Attribute("description").Value }).ToList() }).ToList(); 

    Or recursively, by adding a recursive method Parse to your class: 或者通过向您的类添加一个递归方法Parse来递归:

     public static Category Parse(XElement value) { return new Category { Id = int.Parse(value.Attribute("id").Value), Name = value.Attribute("name").Value, Description = value.Attribute("description").Value, SubCategories = value.Elements().Select(newvalue => Parse(newvalue)).ToList() }; } 

    and calling it like this: 并这样称呼它:

     var categories = x.Root.Elements().Select(e => Category.Parse(e)).ToList(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM