2014-09-30 1 views
0

저는 Linq를 처음 사용하고 있으며 요소의 특정 속성 목록도 문제가 있습니다.Linq 요소 속성 문자열 목록

XML 파일은 다음과 같습니다 특정 태그의 목록을

<configuration> 
    <logGroup> 
    <group name="cpm Log 1h 1y Avg" logInterval="* 1 * * * ?" /> 
    <group name="cpm Log 1d 2y Avg" logInterval="* 10 * * * ?" /> 
    </logGroup> 
    <tagGroup> 
    <tag name="Tag_1"> 
     <property name="VALUE"> 
     <logGroup name="cpm Log 1h 1y Avg" /> 
     <logGroup name="cpm Log 1d 2y Avg" /> 
     </property> 
    </tag> 
    <tag name="Tag_2"> 
     <property name="VALUE"> 
     <logGroup name="cpm Log 1h 1y Avg" /> 
     <logGroup name="cpm Log 1d 2y Avg" /> 
     </property> 
    </tag> 
    <tag name="Tag_3"> 
     <property name="VALUE"> 
     <logGroup name="cpm Log 1h 1y Avg" /> 
     <logGroup name="cpm Log 1d 2y Avg" /> 
     </property> 
    </tag> 
    </tagGroup> 
</configuration> 

내가 원하는 위해. 나는이 코드를 시도

 
"cpm Log 1h 1y Avg" 
"cpm Log 1d 2y Avg" 

:

var tagLogGroups = 
    from logGroupName in xelement 
     .Elements("tagGroup") 
     .Elements("tag") 
     .Elements("property") 
     .Elements("logGroup") 
    where (string)logGroupName.Element("tag") == "Tag_1" 
    select logGroupName.Attribute("name").Value; 
+0

게시 한 코드가 잘못되었습니다. – gunr2171

+1

어제의 [질문] (http://stackoverflow.com/questions/26104412/how-to-access-a-specific-attribute-using-linq-to-xml)과 유사하지 않습니까? 제발 대답을 살펴보고 당신은 linq 쿼리 자신을 알아낼 수있을거야 –

+0

내가 그 사람들의 모든 후 서로의 목록을 얻을 수있는 건,하지만 난 CanT Tag_1에만 logGroup의 af 목록을 얻을. @ 토니 시작 그것은 거의 같은 질문입니다, 나는 목록에 나머지를 가지고 있지만 logGroup 없습니다. 그리고 나는 오랫동안 그것을 보았다 : ( – Hnox

답변

1

당신의 logGroupNamelogGroup 요소처럼

는 그래서 Tag_1입니다이 목록은해야한다. 이 log라는 이름의 자식 요소가없는 그래서, 난 당신이 원하는 생각 :

where (string)logGroupName.Parent.Parent.Attribute("name") == "Tag_1" 

또는 단순히 (별도의 문으로)

var tags = xelement.Descendants("tag") 
    .First(x => (string) x.Attribute("name") == "Tag_1") 
    .Descendants("logGroup") 
    .Select(x => (string)x.Attribute("name")); 
+0

downvoter 시간을내어. –

+0

개인적으로'(문자열) x.Attribute()'대신'x.Attribute(). Value '를 사용하고 싶습니다. 값을 원한다는 것을 의미합니다 (+1도 가능). – gunr2171

1

는 희망이 당신을 이해하는 데 도움이 더 나은

XDocument xDoc = XDocument.Parse("<yourXMLString>"); 

// step 1: get all elements with element name 'tag' from the XML using xDoc.Descendants("tag") 
// step 2: now that we have all 'tag' elements, filter the one with 'name' attribute value 'Tag_1' using `where` 
// step 3: now get all 'logGroup' elements wherever they are within the above filtered list 
// step 4: finally get their attributes 
var temp = xDoc.Descendants("tag") 
       .Where(p => p.Attribute("name").Value == "Tag_1") // here p is just an iterator for results given by above statement 
       .Descendants("logGroup") 
       .Attributes("name"); 

// then you can access the fetched attributes value like below or convert to a list or whatever 
string attrValue = string.Empty; 
foreach (var item in temp) 
{ 
    attrValue = item.Value; 
}