简体   繁体   中英

LINQ to XML select element from specific node/nodes

I have an XML file and would like to create objects based on the content of the file. The XML file looks like:

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

My LINQ statement is the following:

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(); 

So my problem is that I get all the Variable objects that are in the XML file, including the the ones in the child nodes (Task). But I just want the Variable objects that are not in any child node. Just the ones in the Module node.

How must my LINQ query look like to get this?

The Descendants method returns all of the descendant elements. You need to use Elements instead. Try something like this:

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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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