简体   繁体   中英

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? 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 . 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)
        });

您只需使用name.Value ,它是XElement的字符串属性。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM