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 & baby" description="test" />
<category id="3" name="home & 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.
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).
Use LINQ to XML (like you want do). In that case, the code could look something like this:
Or recursively, by adding a recursive method
Parseto your class:and calling it like this: