【问题标题】:LINQ to XML select element from specific node/nodesLINQ to XML 从特定节点/节点中选择元素
【发布时间】:2015-04-14 02:56:42
【问题描述】:

我有一个 XML 文件,想根据文件的内容创建对象。 XML 文件如下所示:

<DefaultView>
    <Module>
      <Variable Name="gTestInt1" Enable="True" />
      <Task Name="Task1">
        <Variable Name="testInt" Enable="True" />
        <Variable Name="testReal" Enable="True" />
        <Variable Name="testString" Enable="True" />
      </Task>
      <Task Name="Task2">
        <Variable Name="testInt1" Enable="True" />
        <Variable Name="testReal" Enable="True" />
        <Variable Name="testString" Enable="True" />
      </Task>
    </Module>
</DefaultView>

我的 LINQ 语句如下:

var globalVariables = (from cfg in _xElements.Descendants("Module").Descendants("Variable")
                      select new Variable
                      {
                          Name = cfg.Attribute("Name").Value,
                          Enable = bool.Parse(cfg.Attribute("Enable").Value)
                      }).ToList(); 

所以我的问题是我获得了 XML 文件中的所有变量对象,包括子节点(任务)中的变量。 但我只想要不在任何子节点中的变量对象。只是 Module 节点中的那些。

我的 LINQ 查询必须是什么样子才能得到这个?

【问题讨论】:

  • 看看XElementElementsDescendants的区别

标签: c# xml linq


【解决方案1】:

Descendants 方法返回所有后代元素。您需要改用Elements。试试这样的:

var globalVariables = (from cfg in _xElements.Descendants("Module")
                                             .Elements("Variable")
                      select new Variable
                      {
                          Name = cfg.Attribute("Name").Value,
                          Enable = bool.Parse(cfg.Attribute("Enable").Value)
                      }).ToList(); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    相关资源
    最近更新 更多