【问题标题】:How to read the attribute of a child node within a node?如何读取节点内子节点的属性?
【发布时间】:2015-09-18 17:34:35
【问题描述】:

我正在尝试读取一个 文件并且我想这样做:

  1. ComboBox 将显示 中的所有蔬菜名称。
  2. 选择蔬菜后,第二个ComboBox 将显示 中的食谱名称,可以使用第一个ComboBox 中选择的蔬菜进行烹饪。
  3. 最后,使用确定按钮,所选配方将读取指向该配方的文件路径。

我写的 XML

<Vegetables>
    <vegetable name="Carrot">
        <recipe name="ABCrecipe">
            <FilePath>C:\\</FilePath>
        </recipe>
        <recipe name="DEFrecipe">
            <FilePath>D:\\</FilePath>
        </recipe>   
    </vegetable>
    <vegetable name="Potato">
        <recipe name="CBArecipe">
            <FilePath>E:\\</FilePath>
        </recipe>
            <recipe name"FEDrecipe">
            <FilePath>F:\\</FilePath>
        </recipe>
    </vegetable>
</Vegetables>

C#代码

public Form1()
{
    InitializeComponent();            
    xDoc.Load("Recipe_List.xml");
}

XmlDocument xDoc = new XmlDocument();

private void Form1_Load(object sender, EventArgs e)
{
    XmlNodeList vegetables = xDoc.GetElementsByTagName("Vegetable");
    for (int i = 0; i < vegetables.Count; i++)
    {
        comboBox1.Items.Add(vegetables[i].Attributes["name"].InnerText);
    }
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    //I'm lost at this place.
}

第一个ComboBox现在可以显示蔬菜名称,但是如何让第二个ComboBox根据文件读取食谱?

【问题讨论】:

    标签: xml xml xml xml c# xml winforms


    【解决方案1】:

    您可以构建以下 Xpath,然后获取蔬菜的配方

    string xpath = string.Format("//vegetable[@name='{0}']/recipe",comboboxSelectedItem);
    var selectedVegetableRecipe = xdoc.SelectSingleNode(xpath);
    

    但是,正如 Ondrej Tucny 指出的,在应用程序启动期间,您可以将 xml 文档缓存在静态 XMLDocument 中,然后在代码中使用它以避免每次调用的性能开销。

    【讨论】:

    • 你是这个意思吗?我对 C# 很陌生,对它不是很熟悉。
    • 是的,代替comboboxSelectedItem,您将投入您的价值。这将执行搜索并为您提供所选变量的配方。请尝试此操作并在此处发布您的更新。
    • 很高兴知道我在正确的道路上,但另一个问题是你向我提出的方法有一个我无法调试的语法错误。哦,不~~~愚蠢的我。
    • 我已经更新了帖子。现在试试吧……我也傻了……comboboxSelectedItem之后不需要报价。
    • 我尝试删除报价,但我想用 selectedVegetableRecipe 做什么?我试图用 messagebox.show 显示它,但由于它是一个 var,所以无法遵守。有什么建议吗?
    【解决方案2】:

    首先,您不会将解析后的 XML 存储在任何地方。因此在comboBox1_SelectedIndexChanged 你不能使用它。您应该在表单中引入私有字段(或属性,等等),而不是 xDoc 局部变量。

    如果您出于某种奇怪的原因想要继续按照您现在使用 XML 文件的方式进行操作,则必须在 comboBox1_SelectedIndexChanged 中查找选定的 &lt;vegetable&gt; 元素,然后处理其所有子 &lt;recipe&gt; 元素.然而,这是不必要的复杂。更好的方法是从声明数据结构开始并使用XML serialization

    您最终会得到两个类,VegetableRecipe,并使用 XmlSerializer序列化(存储到 XML)和 反序列化(读取自XML)你的数据。在表单中,您将使用对象,而不必手动使用 XML。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-18
      • 1970-01-01
      • 2010-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多