簡體   English   中英

linq to xml獲取所有子節點

[英]linq to xml get all child nodes

我正在嘗試查詢包含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個端點。

我想你想要這個:

    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/zh-cn/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查詢的結果是IEnumerables的IEnumerable,因此我采用的First()結果現在為我提供了IEnumerable<XElement> ,然后在其上調用Descendants() ,為您提供端點XElement的IEnumerable。

還要注意,我使用了XAttributeValue屬性,不能簡單地將XAttribute轉換為字符串,必須使用那個Value屬性。 我沒有在最初的復制/粘貼答案中發現這一點。

** 更新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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM