Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting all XML elements and their values dynamically using LINQ

Tags:

c#

xml

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? 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())
 {
 }
like image 230
Chris Lombardi Avatar asked May 17 '26 20:05

Chris Lombardi


2 Answers

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())
   {


   }
like image 138
Bhagyesh Patel Avatar answered May 20 '26 11:05

Bhagyesh Patel


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. 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.

var results =
    doc
        .Descendants("QueryResults")
        .Elements()
        .GroupBy(x => x.Name, (name, items) => new
        {
            Name = name,
            Values = items.Select(x => x.Value)
        });
like image 30
t3chb0t Avatar answered May 20 '26 09:05

t3chb0t



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!