linq到xml获取所有子节点

本文关键字:子节点 获取 xml linq | 更新日期: 2023-09-27 18:21:28

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

<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个端点。

linq到xml获取所有子节点

我想你想要这个:

    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的IEnumeraable,所以我取其First()结果,现在得到IEnumerable<XElement>,然后我们调用Descendants(),这得到端点XElement的IEnumarable。

这里还要注意,我使用了XAttributeValue属性,不能简单地将XAttribute强制转换为字符串,必须使用Value属性。我在最初的复制/粘贴答案中没有发现这一点。

**更新2**

上面的查询can可能更容易理解,如下所示:

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