Reputation: 397
I have an XML with the following structure:
<Categories>
<Category>
<Books>
<Book>
<BookId>1</BookId>
<BookQuantity>150</BookQuantity>
</Book>
<Book>
<BookId>2</BookId>
<BookQuantity>250</BookQuantity>
</Book>
</Books>
</Category>
<Category>
<Books>
<Book>
<BookId>1</BookId>
<BookQuantity>150</BookQuantity>
</Book>
<Book>
<BookId>3</BookId>
<BookQuantity>250</BookQuantity>
</Book>
</Books>
</Category>
</Categories>
I am trying to retrieve each distinct Book with its quantity within the category. The output would be:
Book 1 300
Book 2 250
Book 3 250
Any best method to do this. I tried with linq query but was not able to succeed.
Upvotes: 0
Views: 744
Reputation: 236228
You can use Linq to Xml. Query is simple - just select all Book elements and group them by value of BookId element. Then project each group into anonymous object or instance of book class:
var xdoc = XDocument.Load(path_to_xml);
var books = from b in xdoc.Root.Descendants("Book")
group b by (int)b.Element("BookId") into g
select new {
Id = g.Key,
Quantity = g.Sum(b => (int)b.Element("BookQuantity"))
};
Result:
[
{ "Id": 1, "Quantity": 300 },
{ "Id": 2, "Quantity": 250 },
{ "Id": 3, "Quantity": 250 }
]
Instead of creating anonymous objects you can create instances of Book class:
public class Book
{
public int Id { get; set; }
public int Quantity { get; set; }
}
Upvotes: 3