[英]Linq query on XML to Select multiple elements of subnodes
我想從以下xml中選擇子項的所有不同值
<root>
<parent>
<child>value 1</child>
<child>value 2</child>
</parent>
<parent>
<child>value 1</child>
<child>value 4</child>
</parent>
</root>
我嘗試了以下操作:
var vals = (from res in XmlResources.Elements("root").Elements("parent") select res)
.SelectMany(r => r.Elements("child")).Distinct().ToList();
但是無法從中獲取價值,給我包裹在標簽中的價值,而不是獨特的價值
是否有可能顯示兩種獲取方式-查詢和鏈接又名lambda。
您正在選擇元素,並且所有元素都是不同的。 您需要獲取不同的值 。 例如:
var values = XmlResources.Element("root")
.Elements("parent")
.Elements("child")
.Select(x => x.Value)
.Distinct();
在這里使用查詢表達式確實沒有任何好處-它只會增加麻煩。 我僅在查詢具有多個方面(例如,where 和有意義的選擇或聯接)時才使用查詢表達式。 對於只是選擇還是只是毫無意義的地方。 是的,您可以使用:
var values = (from x in XmlResources.Element("root")
.Elements("parent")
.Elements("child")
select x.Value).Distinct();
...但是你為什么呢? 海事組織還不清楚。
請注意,如果您不太關心根/父/子層次結構,並且很高興獲得所有 child
后代,則可以使用:
var values = XmlResources.Descendants("child")
.Select(x => x.Value)
.Distinct();
是的,雙向都有可能
var doc = new XDocument("your xml string");
var values = (from c in doc.Root.Descendants("child") select c.Value).Distinct();
//鏈式
var values = doc.Root.Descendants("child").Select(c=>c.Value).Distinct();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.