LINQ - 从具有特定标记的 XML 元素中选择 *
本文关键字:XML 元素 选择 LINQ | 更新日期: 2023-09-27 18:31:38
我一直在从以下链接中查看 LINQ 的示例;我已经在链接下方发布了代码。
是否可以修改此示例,以便var
中返回的项目包含在与文档匹配的项中找到的所有子元素。后代("人")过滤器? 我基本上希望这个 XML 查询像 SQL 选择 * 一样,这样我就不必像 drink、moneySpents 和 zipCode 那样显式指定字段名称。
http://broadcast.oreilly.com/2010/10/understanding-c-simple-linq-to.html#example_1
static void QueryTheData(XDocument doc)
{
// Do a simple query and print the results to the console
var data = from item in doc.Descendants("person")
select new
{
drink = item.Element("favoriteDrink").Value,
moneySpent = item.Element("moneySpent").Value,
zipCode = item.Element("personalInfo").Element("zip").Value
};
foreach (var p in data)
Console.WriteLine(p.ToString());
}
OP 说他喜欢发布的答案,所以我会重新提交它以供科学:)
var data = from item in doc.Descendants("person")
select item;
唯一的问题是数据是一个IEnumerable<XElement>
,你必须通过字符串名称查询字段。
// Do a simple query and print the results to the console
var data = from item in doc.Descendants("person")
select item;