2014-09-30 121 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> 

我想要得到一個特定的標籤列表。

所以到TAG_1這個名單應該是這樣的:

 
"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 2014-09-30 13:40:46

+1

這是不是類似於你昨天的[問題](http://stackoverflow.com/questions/26104412/how-to-access-a-specific-attribute-using-linq-to-xml)?請看看答案,你可以自己找出linq查詢 – 2014-09-30 13:49:14

+0

我可以把它們全部列出來,然後我不能得到Tag_1中只有logGroup的列表。 @Tony啓動它幾乎是同一個問題,我把剩下的放到了列表中,但沒有將它們放到logGroup中。我已經看了很長一段時間:( – Hnox 2014-09-30 13:58:40

回答

1

logGroupNamelogGroup元素。因此,它沒有名爲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把你的時間。 – 2014-09-30 13:51:00

+0

我個人喜歡使用'x.Attribute()。Value'而不是'(字符串)x.Attribute()',使它更清晰你想要的價值。(也+1)。 – gunr2171 2014-09-30 13:57:53

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; 
} 
相關問題