我有一个看起来像的 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,
};
最佳答案
给定您的 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 建立的相同层次结构。当然,您可以根据需要将其展平为一个级别。
关于c# - Linq:如何获取二级节点的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7355689/