Selecting all XML elements and their values dynamically using LINQ
I have the following code that dynamically selects all individual item names; I also want to see the values for these elements. How can I do this using LINQ? I am open to this in other ways as well.
XDocument doc = XDocument.Load("XMLFile1.xml");
foreach (var name in doc.Descendants("QueryResults").Elements()
.Select(x => x.Name).Distinct())
{
}
+3
source to share
3 answers
The accepted query is different from the original one because it changes the way it works Distinct
, because it no longer only compares Name
as well Value
. If you want to see what names have values that you need to use GroupBy
in Name
and get Value
for each item.
var results =
doc
.Descendants("QueryResults")
.Elements()
.GroupBy(x => x.Name, (name, items) => new
{
Name = name,
Values = items.Select(x => x.Value)
});
+1
source to share