简体   繁体   中英

Retrieve all child elements' values (Linq Query)

I'm trying to get a collection of values from an XML document:

<root>
  <string id = "STRING_ID">
    <control>
      <type> Label </type>
      <type> Form </type>
      <type> ... </type>
    </control>
  </string>
</root>

I have a checkbox control in my application. Based on which string is selected in a datagridview, I query the XDocument as follows:

var controls = from str in xdoc.Descendants("string")
                           where str.Attribute("id").Value == tagBox.Text
                           from cont in str.Descendants("control")
                           where cont.HasElements
                           select cont.Elements();

And the aim is to refresh the checkbox with the proper boxes checked to indicate what kind of control the string belongs to. Multiple values are allowed. At this point, I can only retrieve one value, even if there are several <type> children for any given <control> parent.

I know this isn't right, but I'm trying to retrieve all the <type> values present in any given <string> within its child <control> .

I will then use this code:

 foreach (var co in controls)
    controlsBox.SetItemChecked(controlsBox.Items.IndexOf(pr.), true);

To set the appropriate items checked. Any ideas?

        var controls = from str in xdoc.Elements("string")
                       where str.Attribute("id").Value == tagBox.Text
                       from cont in str.Elements("control")
                       from type in cont.Elements("type")
                       select type;

Or, even simpler:

        var controls = from str in xdoc.Elements("string")
                       where str.Attribute("id").Value == tagBox.Text
                       from type in str.Elements("control").Elements("type")
                       select type;

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