我正在尝试从XML文档中获取值集合:
<root>
<string id = "STRING_ID">
<control>
<type> Label </type>
<type> Form </type>
<type> ... </type>
</control>
</string>
</root>
我的应用程序中有一个复选框控件。根据在datagridview中选择的字符串,我按如下方式查询XDocument:
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();
目的是刷新复选框并选中正确的方框以指示字符串属于哪种控件。允许多个值。此时,我只能检索一个值,即使任何给定的<type>
父级都有多个<control>
个孩子。
我知道这不对,但我正在尝试检索其子<type>
内任何给定<string>
中存在的所有<control>
值。
然后我将使用此代码:
foreach (var co in controls)
controlsBox.SetItemChecked(controlsBox.Items.IndexOf(pr.), true);
设置选中的相应项目。 有什么想法吗?
答案 0 :(得分:1)
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;