繁体   English   中英

如何使用LINQ to XML访问特定属性

[英]How to access a specific attribute using LINQ to XML

我希望访问XML文件中的某些特定属性(标记名称),并将它们放置在列表中,但我无法正确理解。 我究竟做错了什么??

该列表应如下所示:

Tag_1
Tag_2
Tag_3

码:

XElement xelement = XElement.Load("C:/...../Desktop/Testxml.xml");
var tagNames = from tag in xelement.Elements("tagGroup")
               select tag.Attribute("name").Value;
foreach (XElement xEle in tagNames)
{
    //....
}

这是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>

只需将您的linq查询更改为:

var tagNames = from tag in xelement.Elements("tagGroup").Elements("tag")
        select tag.Attribute("name").Value;

然后tagName是IEnumerable <string> ,您可以像这样迭代:

foreach (var element in tagNames)
{
    //element is a string
}

您的代码枚举名为tagGroup的元素,然后尝试获取名为name的属性。 tagGroup中没有属性。 实际上,tagGroup具有两个称为logGroup的后代。 具有名称属性的logGroup。

此代码将不起作用:

XElement xelement = XElement.Load("C:/...../Desktop/Testxml.xml");
var tagNames = from tag in xelement.Elements("tagGroup")
                   select tag.Attribute("name").Value;

您需要的是类似

var tagGroups = xelement.Descendants("tag").Select(x => x.Attribute("name")).ToList();

或者,如果您想要其他人:

var tagGroups = xelement.Descendants("logGroup").Select(x => x.Attribute("name")).ToList();
var tagGroups = xelement.Elements("tagGroup").ToList();
var logGroups = tagGroups.SelectMany (g => g.Descendants("logGroup")).ToList();
var logAttributes = tagGroups.SelectMany (g => g.Descendants("logGroup").Select(x => x.Attribute("name"))).ToList();

尝试这个...

var tagNames = from tag in xelement.Elements("tagGroup").Elements("tag")
               select tag.Attribute("name").Value;

要么

var tagNames = xelement.Elements("tagGroup")
                       .Elements("tag")
                       .Attribute("name").Value;

就像是 :

var tagNames = xe.Element("tagGroup").Elements("tag").Select(a => a.Attribute("name").Value);
foreach (var xEle in tagNames)
        {
            Console.WriteLine(xEle);
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM