Linq:如何获取二级节点的值

本文关键字:二级 节点 获取 何获取 Linq | 更新日期: 2023-09-27 18:08:17

我有一个看起来像

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

获取title元素没有问题,但是当我试图获取price中的所有值时,它不起作用。

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

Linq:如何获取二级节点的值

给定您的XML片段,此代码可以填充对象序列

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

该结构遵循与XML建立的相同的层次结构。当然,如果你愿意,你也可以把它平铺成一个平面。

我将货币和金额元素的大小写改为title大小写,效果很好。

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

XML区分大小写