Linq元素属性字符串列表
本文关键字:列表 字符串 属性 元素 Linq | 更新日期: 2023-09-27 18:25:02
我是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日志1小时1年平均值"cpm日志1d 2y平均值"
我尝试过这个代码:
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;
您的logGroupName
是logGroup
元素。所以它没有一个名为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"));
希望这能帮助您更好地理解
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;
}