Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检索所有子元素';值(Linq查询)_C#_.net_Xml_Linq - Fatal编程技术网

C# 检索所有子元素';值(Linq查询)

C# 检索所有子元素';值(Linq查询),c#,.net,xml,linq,C#,.net,Xml,Linq,我试图从XML文档中获取一组值: <root> <string id = "STRING_ID"> <control> <type> Label </type> <type> Form </type> <type> ... </type> </control> </string> </root>

我试图从XML文档中获取一组值:

<root>
  <string id = "STRING_ID">
    <control>
      <type> Label </type>
      <type> Form </type>
      <type> ... </type>
    </control>
  </string>
</root>
其目的是使用选中的适当框刷新复选框,以指示字符串属于哪种控件。允许使用多个值。此时,我只能检索一个值,即使对于任何给定的
父级,都有几个
子级

我知道这是不对的,但我正在尝试检索其子
中任何给定
中存在的所有

然后我将使用以下代码:

 foreach (var co in controls)
    controlsBox.SetItemChecked(controlsBox.Items.IndexOf(pr.), true);
要设置相应的项目,请选中。 有什么想法吗

        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;
或者更简单一点:

        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;

谢谢你的回复。建议的查询是否应该检索这些值?我想是的,但不确定,因为当我运行程序时,我的问题中的
foreach
也应该在控制台上打印
var控件中的每个值,然后再尝试选中checkbox控件中的任何框。此查询返回所有
元素(但是你可能想选择
type.Value
而不仅仅是
type
)嗯,似乎仍然有问题。看起来
控件
返回为空。让它工作起来了。关键是我必须将
xdoc.Elements(“字符串”)
更改为
xdoc.substands(“字符串”)
。再次感谢Thomas!@Sean,实际上你应该这样做。
xdoc.Root.Elements(“string”)
元素
子体
更快,因为它不会递归搜索。当你知道文档的确切结构时,最好使用
元素
        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;