如何从XML文档中读取值以构建ComboBox?

Meo*_*eow 6 c# xml winforms

我正在尝试读取我想为妈妈制作的文件.基本上这就是我想做的事情:

  1. A ComboBox将显示XML中的所有蔬菜名称.
  2. 选择蔬菜后,第二个ComboBox将显示XML中的食谱名称,该名称可以使用在第一个菜单中选择的蔬菜ComboBox进行烹饪.
  3. 最后,通过OK Button,所选配方将读取通向配方的文件路径.

我写的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>
Run Code Online (Sandbox Code Playgroud)

C#代码

private void Form1_Load(object sender, EventArgs e)
{
    XmlDocument xDoc = new XmlDocument();
    xDoc.Load("Recipe_List.xml");
    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.
}
Run Code Online (Sandbox Code Playgroud)

第一个ComboBox现在能够显示蔬菜名称,但如何让第二个ComboBox阅读食谱?

Sam*_*uel 1

您的 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>
Run Code Online (Sandbox Code Playgroud)

因此,要显示菜谱,您需要提取菜谱节点的属性。这里解释了如何做到这一点:How to read attribute value from XmlNode in C#?

编辑:由于注释更正了 xml 结构。谢谢