I am new to LINQ to XML and need help in mapping an XML hierarchy into my domain object. Here is the XML source:
<?xml version="1.0" encoding="UTF-8"?>
<Listings>
<Region>United States</Region>
<Listing>
<CatID>ELE</CatID>
<CatDesc>Electronics</CatDesc>
<ItemID>ELE_LCDTV</ItemID>
<ItemDesc>LCD TV BLU RAY</ItemDesc>
<TotalPrice>1500</TotalPrice>
</Listing>
<Listing>
<CatID>COMP</CatID>
<CatDesc>Computer</CatDesc>
<ItemID>COMP_LAPTOP</ItemID>
<ItemDesc>Laptop HP</ItemDesc>
<TotalPrice>1200</TotalPrice>
</Listing>
<Listing>
<CatID>MISC</CatID>
<CatDesc>Miscellaneous</CatDesc>
<ItemID>MISC_WII</ItemID>
<ItemDesc>Wii</ItemDesc>
<TotalPrice>350</TotalPrice>
</Listing>
<Listing>
<CatID>COMP</CatID>
<CatDesc>Computer</CatDesc>
<ItemID>COMP_HD</ItemID>
<ItemDesc>Hard Disk</ItemDesc>
<TotalPrice>300</TotalPrice>
</Listing>
<Listing>
<CatID>ELE</CatID>
<CatDesc>Electronics</CatDesc>
<ItemID>ELE_IPOD</ItemID>
<ItemDesc>iPod</ItemDesc>
<TotalPrice>225</TotalPrice>
</Listing>
<Listing>
<CatID>COMP</CatID>
<CatDesc>Computer</CatDesc>
<ItemID>COMP_WKEY</ItemID>
<ItemDesc>Wireless Keyboard</ItemDesc>
<TotalPrice>110</TotalPrice>
</Listing>
<Listing>
<CatID>MISC</CatID>
<CatDesc>Miscellaneous</CatDesc>
<ItemID>MISC_GAME</ItemID>
<ItemDesc>Games</ItemDesc>
<TotalPrice>50</TotalPrice>
</Listing>
</Listings>
I have to populate following domain objects ushing above XML. Basically I have to expose an IEnumerable ListCategories()
public class Category
{
public string ID { get; set; }
public string Description { get; set; }
public IList<Item> Items { get; set; }
}
public class Item
{
public string ID { get; set; }
public string Description { get; set; }
public decimal TotalPrice { get; set; }
}
I undersyand that I have to an orderby query first to sort the XML by CatID and then traverse through it to populate my domain objects.
XDocument xDoc = XDocument.Parse(XmlizedString);
var listing = from x in xDoc.Elements("Listings").Elements("Listing")
orderby (string)x.Element("CatID")
select x;
Above query will sort my XML by CatID but I am not clear how to proceed further...
I would gretly appreciate your suggestions/help in resolving this.