简体   繁体   中英

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. I have loaded the XML as an XDocument (by reading the XML from a file into a string first). I need some guidance on how I should parse this.

Example string read from XML file as

<?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:

[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).

  2. Use LINQ to XML (like you want do). 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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