gpt4 book ai didi

c# - linq to xml 获取所有子节点

转载 作者:行者123 更新时间:2023-12-03 22:16:15 29 4
gpt4 key购买 nike

我正在尝试查询 web.Config包含 WCF 条目的文件。

<service>节点有一个 name attribute我正在尝试匹配。到目前为止,我的代码在进行匹配时有效,但我的问题是它只返回 <endpoint> 中的 1 个。节点。

例如我可以有这个 xml 片段:

<service name="a">
<endpoint>1</endpoint>
<endpoint>2</endpoint>
<endpoint>3</endpoint>
</service>
<service name="b">
<endpoint>1</endpoint>
<endpoint>2</endpoint>
</service>

每次我得到匹配项时,我都希望它显示所有 <endpoint>该匹配项的子节点。

这是我目前的代码:

        IEnumerable<XElement> xmlURL =
from el in xmlFile.Root.Descendants("service")
where (string)el.Attribute("name") == serviceString
select el.Element("endpoint");

Console.WriteLine("Start: " + serviceString);
foreach (XElement el in xmlURL)
{
Console.WriteLine(el);
}
Console.WriteLine("End: " + serviceString + "\n\n");

目前,当它进行匹配时,仅显示 1 个端点。

最佳答案

我想你想要这个:

    IEnumerable<XElement> xmlURL =
from el in xmlFile.Root.Descendants("service")
where (string)el.Attribute("name") == serviceString
select el.Descendants("endpoint");

Console.WriteLine("Start: " + serviceString);
foreach (XElement el in xmlURL)
{
Console.WriteLine(el);
}
Console.WriteLine("End: " + serviceString + "\n\n");

注意我选择了el.Descendants()而不是 Element()它只会返回第一个匹配项 ( http://msdn.microsoft.com/en-us/library/system.xml.linq.xcontainer.element.aspx )。

** 更新 **

我认为这就是您想要的,因为您只关心一个特定匹配项。

IEnumerable<XElement> xmlURL = 
(from el in doc.Root.Descendants("service")
where el.Attribute("name").Value == serviceString
select el).First().Descendants();

因此,正如编译器告诉您的那样,LINQ 查询的结果是 IEnumerable 的 IEnumerable,因此我采用 First()结果现在给了我一个 IEnumerable<XElement> , 然后我们调用 Descendants()在那上面,它为您提供了端点 XElement 的 IEnumerable的。

另请注意,我使用了 Value XAttribute 的属性(property),你不能简单地转换 XAttribute到一个字符串,你必须使用那个 Value属性(property)。我在最初的复制/粘贴回答中没有注意到这一点。

** 更新 2 **

上面的查询可能像这样更容易理解:

doc.Root.Descendants("service")
.Where(x => x.Attribute("name").Value == serviceString)
.First()
.Descendants();

** 更新 3 **

在属性匹配上也有 NRE 的潜力,所以这可能是一个更好的版本。 =)

doc.Root.Descendants("service")
.Where(x => x.Attribute("name") != null && x.Attribute("name").Value == serviceString)
.First()
.Descendants();

关于c# - linq to xml 获取所有子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9025437/

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