2015-01-16 1 views
0

나는이 같은 XML이 :Xml Linq를 사용하여 여러 수준의 특성 값을 검색하는 방법은 무엇입니까?

<?xml version="1.0" encoding="iso-8859-1" ?> 
<Menu> 
    <Group Flow="Horizontal"> 
     <Item Text="Basket" > 
     <Item Text="Favorites"> 
     <Item Text="Add" Roles="SuperAdmin"> 
       <Item Text="Evaluation" Roles="Admin"> 
       </Item> 
       <Item Text="Titularisation" Roles="users,Admin"> 
       </Item> 
     </Item> 
    </Group> 
</Menu> 

을 나는 모두가 "역할" 속성 검색 할.

나는이 시도 :

XElement rootElement = XElement.Load(@"C:\Users\TTM\Desktop\GeneralMenu.xml"); 
    XElement menuElt = rootElement.Element("Group"); 
    var itemsAdd = from el in menuElt.Descendants("Item") 
         where (string)el.Attribute("Text") == "Add" 
         select el; 
    foreach (var item in itemsAdd) 
    { 
     Console.WriteLine(item.Attribute("Roles").Value); 
    } 

    Console.Read(); 

을하지만 난 단지 "역할"이 발리의 수 :

<Item Text="Add" Roles="SuperAdmin"> 
+0

당신 Text = "Add"로만 항목을 선택하면 itemsAdd- collection을 채 웁니다. 그래, 그래. –

+0

예. 알아. 나는 다음과 같이하려고했다 :'XElement itemAdd = from menuElt.Descendants ("Item") where (string) el.Attribute ("Text") == "추가" select el; – mosflex

답변

1

을이 시도 : - 여기

XDocument xdoc = XDocument.Load(XMLFile); 
var itemAdd = xdoc.Descendants("Item") 
       .Where(x => (string)x.Attribute("Text") == "Add") 
       .Select(x => new 
{ 
    Roles = (string)x.Attribute("Roles"), 
    ChildRoles = x.Descendants("Item") 
        .Select(z => (string)z.Attribute("Roles")).ToList() 
}); 

, Roles 부모 노드의 역할이 포함되며 ChildRoles은 Text가 Add 인 하위의 모든 역할을 보유합니다.

그런 다음 foreach 루프를 사용하여 액세스 할 수 있습니다 - 당신이 모든 역할은 하나의 속성에 가져올 수하려면

foreach (var item in itemAdd) 
{ 
    Console.WriteLine(item.Roles); 
    foreach (var childRoles in item.ChildRoles) 
    { 
     Console.WriteLine(childRoles); 
    } 
} 

는 다음과 같이 그것을 가져올 수 : -

Roles = x.Descendants("Item").Select(z => (string)z.Attribute("Roles")) 
     .Concat(new List<string> { (string)x.Attribute("Roles") }).ToList() 
+0

Ok. 결과를 어떻게 표시 할 수 있습니까? – mosflex

+0

@mosflex - 내 편집 결과를 표시하는 방법을 확인하십시오. –

+1

정말 고마워요 !! – mosflex

관련 문제