如何使用LINQ to XML访问特定属性 [英] How to access a specific attribute using LINQ to XML

查看:65
本文介绍了如何使用LINQ to XML访问特定属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wish to access some specific attribute (Tag name) i an XML file, and place them in a list but i cant get i right. What am I doing wrong??

列表应如下所示:

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>

推荐答案

尝试一下...

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;

这篇关于如何使用LINQ to XML访问特定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆