[英]Selecting all XML elements and their values dynamically using LINQ
I have the following code which dynamically selects all of the distinct element names, however; 我有以下代码,动态选择所有不同的元素名称; I also want to see the values for these elements.
我也想看看这些元素的值。 How can I do this using LINQ?
我怎么能用LINQ做到这一点? I am open to doing it other ways as well.
我也乐于采取其他方式。
XDocument doc = XDocument.Load("XMLFile1.xml");
foreach (var name in doc.Descendants("QueryResults").Elements()
.Select(x => x.Name).Distinct())
{
}
Something like this would work 像这样的东西会起作用
XDocument doc = XDocument.Load("XMLFile1.xml");
foreach (var name in doc.Descendants("QueryResults").Elements()
.Select(x => new {Name = x.Name, Value = e.Value}).Distinct())
{
}
The accepted query is differnt then the original one because it changes how Distinct
works because it no longer compares only Name
but also Value
. 接受的查询与原始查询不同,因为它会更改
Distinct
工作方式,因为它不再仅比较Name
,还会比较Value
。 If you want to see which names have which values you need to use GroupBy
on the Name
and get the Value
for each item. 如果要查看哪些名称具有哪些值,则需要在
Name
上使用GroupBy
并获取每个项目的Value
。
var results =
doc
.Descendants("QueryResults")
.Elements()
.GroupBy(x => x.Name, (name, items) => new
{
Name = name,
Values = items.Select(x => x.Value)
});
您只需使用name.Value
,它是XElement
的字符串属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.