繁体   English   中英

使用LINQ动态选择所有XML元素及其值

[英]Selecting all XML elements and their values dynamically using LINQ

我有以下代码,动态选择所有不同的元素名称; 我也想看看这些元素的值。 我怎么能用LINQ做到这一点? 我也乐于采取其他方式。

 XDocument doc = XDocument.Load("XMLFile1.xml");
 foreach (var name in doc.Descendants("QueryResults").Elements()
                .Select(x => x.Name).Distinct())
 {
 }

像这样的东西会起作用

   XDocument doc = XDocument.Load("XMLFile1.xml");
   foreach (var name in doc.Descendants("QueryResults").Elements()
                .Select(x => new {Name = x.Name, Value = e.Value}).Distinct())
   {


   }

接受的查询与原始查询不同,因为它会更改Distinct工作方式,因为它不再仅比较Name ,还会比较Value 如果要查看哪些名称具有哪些值,则需要在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.

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