2012-07-10 15 views
3

모든 부모 :C#을 XML 노드를 찾아 내가 좋아하는 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)); 

내 노드를 반환 C# Linq to XML, get parents when a child satisfy condition

에서

<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> 

나는 이런 식으로 뭔가있어 및 그 부모. 어떻게하면 될 것 내 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이 될 때까지 발견 된 부모에,하지만 더 나은 (청소기) 방법이 무엇입니까?

답변

5

AncestorsAndSelf 메서드는 필요한 모든 작업을 수행하며 모든 부모 수준에서 요소의 조상을 찾습니다. 자손의 방법은 모든 수준에서 이름으로 요소를 찾아 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(); 
    } 
+0

작품을 완벽하게 – user1291518

+0

좋아요, 내가 도울 기쁘다합니다. –

관련 문제