Linq Elements属性字符串列表

时间:2014-09-30 13:39:04

标签: c# 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;

2 个答案:

答案 0 :(得分: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"));

答案 1 :(得分: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;
}