首页 > 解决方案 > 仅从一个分支读取子节点

问题描述

我在这里查看了几个示例,看起来我正在遵循正确的程序但它仍然无法正常工作,所以我显然做错了。我有两个组合框,我试图从 XML 文件中填充这个想法是,一旦做出第一个选择,就会生成第二个组合框的一组选择,如果我切换第一个选择,那么第二个组合框应该刷新为好

这是我的 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 是否错误或我调用子节点的方式。

标签: c#comboboxxmldocumentxmlnodechild-nodes

解决方案


我检查了您的代码,并进行了以下更改。

1. XML 文件

Customer 节点已关闭并且没有嵌套 Data/System 节点。这会产生以下两个 xpath:

  1. 组合框/客户;
  2. 组合框/数据/系统;

通过在 Customer 节点内嵌套 Data/System 节点是解决方案的第一部分:

<?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>

2.代码的变化

XML 结构中的更改简化了“node.SelectNodes()”语句中的 xpath 使用,只包含“Data/System”。我还将“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);
        }
    }
}

3.删除这个块

因为客户列表需要它的项目在运行时已经存在。手动将项目添加到组合框并删除此块:

foreach (XmlNode node in customerList)
{
    customer_comboBox.Items.Add(node.Attributes["name"].InnerText);
}

推荐阅读