2014-09-30 133 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; 
} 
相关问题