C# 检索所有子元素';值(Linq查询)
我试图从XML文档中获取一组值: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>
<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;