繁体   English   中英

仅从一个分支读取子节点

[英]Read child node from one branch only

我在这里查看了几个示例,看起来我正在遵循正确的程序但它仍然无法正常工作,所以我显然做错了。 I have two comboBox which I am trying to populate from an XML file The idea is that once the first selection has been made the set of choices for the secondary comboBox will be generated and if i switch the first selection then the secondary comboBox should refresh as出色地

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

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

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 的使用,只包含“数据/系统”。 我还将“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.删除此块

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM