3

次のようなXML構造を取得しました。

<siteNode controller="a" action="b" title="">
  <siteNode controller="aa" action="bb" title="" />
  <siteNode controller="cc" action="dd" title="">
    <siteNode controller="eee" action="fff" title="" />
  </siteNode>
</siteNode>

C#LinqからXMLまで 、子が条件を満たすときに親を取得する

私はこのようなものを手に入れました:

XElement doc = XElement.Load("path");
var result = doc.Elements("siteNode").Where(parent =>
  parent.Elements("siteNode").Any(child => child.Attribute("action").Value ==
  ActionName && child.Attribute("controller").Value == ControlerName));

これは私のノードとその親を返します。ノードの親だけでなく、その「祖父母」、つまり親の親などを取得するにはどうすればよいでしょうか。つまり、私のXMLでは次のようになります。

<siteNode controller="eee" action="fff" title="" /> 
with parent 
<siteNode controller="cc" action="dd" title="" >
with parent
<siteNode controller="a" action="b" title="" >

明らかな答えは、見つかった親に対してそのlinq式をnullになるまで使用することですが、より良い(よりクリーンな)方法はありますか?

4

1 に答える 1

5

AncestorsAndSelfメソッドは、必要なことを正確に実行し、すべての親レベルで要素の祖先を検索します。Descendantsメソッドは任意のレベルで名前で要素を検索し、FirstOrDefaultメソッドは基準に一致する最初の要素を返します。一致する要素が見つからない場合はnullを返します。

    XElement el = doc.Descendants("siteNode")
                    .FirstOrDefault(child => 
                        child.Attribute("action").Value == ActionName 
                        && 
                        child.Attribute("controller").Value == ControlerName);
    if (el != null)
    {
        var result2 = el.AncestorsAndSelf();
    }
于 2012-07-10T11:21:48.700 に答える