我在这里看了几个例子,看起来我遵循了正确的程序,但它仍然没有工作,所以我显然做错了什么。我有两个comboBox,我试图从一个XML文件中填充,我的想法是,一旦第一个选择已经做出了,将生成一组选择的第二个comboBox,如果我切换第一个选择,然后第二个comboBox应该刷新以及。
这是我的XML
<?xml version="1.0" encoding="utf-8"?>
<ComboBox>
<Customer name="John"/>
<Data>
<System>Linux</System>
</Data>
<Customer name="Fernando"/>
<Data>
<System>Microsoft</System>
<System>Mac</System>
</Data>
</ComboBox>
这是我的C#代码
//This part works the customer_comboBox is generated correctly with John and Fernando
XmlDocument doc = new XmlDocument();
doc.Load(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +@"\comboBox.xml");
XmlNodeList customerList = doc.SelectNodes("ComboBox/Customer");
foreach (XmlNode node in customerList)
{
customer_comboBox.Items.Add(node.Attributes["name"].InnerText);
}
//putting the selected item from the first comboBox in a string
string selected_customer = customer_comboBox.SelectedItem.ToString();
//This is the part that does not work
//I want to read XML node that matches selected_customer and populate systems available
foreach (XmlNode node in customerList)
{
if (node.Attributes["name"].InnerText == selected_customer)
{
foreach (XmlNode child in node.SelectNodes("ComboBox/Customer/Data"))
{
system_comboBox.Items.Clear();
system_comboBox.Items.Add(node["System"].InnerText);
}
}
}
我连续两天都在想办法解决这个问题。不知道是我的XML出了问题还是我调用子节点的方式出了问题。
我已经检查了你的代码,我有以下的变化。
客户节点被关闭,并没有嵌套DataSystem节点。这就导致了以下两个xpath。
通过将DataSystem节点嵌套在Customer节点里面,是解决了第一部分问题。
<?xml version="1.0" encoding="utf-8" ?>
<ComboBox>
<Customer name="John">
<Data>
<System>Linux</System>
</Data>
</Customer>
<Customer name="Fernando">
<Data>
<System>Microsoft</System>
<System>Mac</System>
</Data>
</Customer>
</ComboBox>
XML结构的改变简化了 "node.SelectNodes() "语句中的xpath用法,只包含 "DataSystem"。我还将 "node["System"].InnerText "简化为 "child.InnerText"。
foreach (XmlNode node in customerList)
{
if (node.Attributes["name"].InnerText == selected_customer)
{
system_comboBox.Items.Clear();
foreach (XmlNode child in node.SelectNodes("Data/System"))
{
system_comboBox.Items.Add(child.InnerText);
}
}
}
因为客户列表需要它的项目在运行时已经存在。手动将项目添加到组合框中,并删除此块。
foreach (XmlNode node in customerList)
{
customer_comboBox.Items.Add(node.Attributes["name"].InnerText);
}