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.
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; }
}
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.