gpt4 book ai didi

c# - Linq 查询 XML 以选择子节点的多个元素

转载 作者:太空宇宙 更新时间:2023-11-03 20:24:26 27 4
gpt4 key购买 nike

我想从以下 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();

但无法从中获取值(value),给我包装在标签中的值(value)而不是 Distinct

是否可以显示获取它的两种方式 - 查询和链接 aka lambda。

最佳答案

是的,这两种方式都是可能的

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

关于c# - Linq 查询 XML 以选择子节点的多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11391653/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com