Yang
Yang

Reputation: 6892

Linq: how to get values of second level nodes

I have an xml that looks like

<response>
 <book>
   <title>Harry Potter</title>
   <Price>
        <Currency>USD</Currency>
        <Amount>$19.89</Amount>
   </Price>
</book>
</response>

I have no problem getting the title element, but when I'm trying to get all values within price, it doesn't work.

var prices = from price in xmlDoc.Descendants("Price")
             select new
             {
                  currency = price.Element("currency").Value,
                  amount = price.Element("amount").Value,
             };

Upvotes: 1

Views: 1669

Answers (2)

Enigmativity
Enigmativity

Reputation: 117064

I changed the casing of the currency and amount elements to title casing and it worked fine.

var prices =
    from price in xmlDoc.Descendants("Price")
    select new
    {
        currency = price.Element("Currency").Value,
        amount = price.Element("Amount").Value,
    };

XML is case-sensitive.

Upvotes: 2

Anthony Pegram
Anthony Pegram

Reputation: 126884

Given your XML snippet, this code can populate a sequence of objects

var books = from book in document.Descendants("book")
            let title = book.Element("title").Value
            let price = book.Element("Price")
            let currency = price.Element("Currency").Value
            let amount = price.Element("Amount").Value
            select new
            {
                Title = title,
                Price = new
                {
                    Currency = currency,
                    Amount = amount
                }
            };

This structure follows the same hierarchy as established by the XML. You can, of course, flatten it into a single level if you wish.

Upvotes: 4

Related Questions