简体   繁体   English

在XML上进行Linq查询以选择多个子节点元素

[英]Linq query on XML to Select multiple elements of subnodes

I want to select all distinct values of child from following xml 我想从以下xml中选择子项的所有不同值

<root>
  <parent>
    <child>value 1</child>
    <child>value 2</child>
  </parent>
  <parent>
    <child>value 1</child>
    <child>value 4</child>
  </parent>
</root>

I tried following: 我尝试了以下操作:

var vals  = (from res in XmlResources.Elements("root").Elements("parent") select res)
                                        .SelectMany(r => r.Elements("child")).Distinct().ToList();

But can't get the value from it, gives me value wrapped in tag and not Distinct 但是无法从中获取价值,给我包裹在标签中的价值,而不是独特的价值

Is it possible to show both ways to get it - query and chaining aka lambda. 是否有可能显示两种获取方式-查询和链接又名lambda。

You're selecting the elements, and the elements are all distinct. 您正在选择元素,并且所有元素都是不同的。 You need to get the distinct values . 您需要获取不同的 For example: 例如:

var values = XmlResources.Element("root")
                         .Elements("parent")
                         .Elements("child")
                         .Select(x => x.Value)
                         .Distinct();

There's really no benefit in using a query expression here - it only adds cruft. 在这里使用查询表达式确实没有任何好处-它只会增加麻烦。 I only use a query expression when the query has multiple aspects to it (eg a where and a meaningful select, or a join). 我仅在查询具有多个方面(例如,where 有意义的选择或联接)时才使用查询表达式。 For just a select or just a where it's pretty pointless. 对于只是选择还是只是毫无意义的地方。 So yes, you can use: 是的,您可以使用:

var values = (from x in XmlResources.Element("root")
                                    .Elements("parent")
                                    .Elements("child")
              select x.Value).Distinct();

... but why would you? ...但是你为什么呢? It's a lot less clear IMO. 海事组织还不清楚。

Note that if you don't care too much about the root/parent/child hierarchy, and are happy to just get all the child descendants, you can use: 请注意,如果您不太关心根/父/子层次结构,并且很高兴获得所有 child后代,则可以使用:

var values = XmlResources.Descendants("child")
                         .Select(x => x.Value)
                         .Distinct();

yes it is possible both ways 是的,双向都有可能

var doc = new XDocument("your xml string");
var values = (from c in doc.Root.Descendants("child") select c.Value).Distinct();

//chaining style //链式

var values = doc.Root.Descendants("child").Select(c=>c.Value).Distinct();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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