我正在尝试阅读xml /questions/tagged/xml我想为我妈妈制作的文件。所以基本上这就是我想做的:
- A
ComboBox
这将显示 XML 中的所有蔬菜名称。
- 选择一种蔬菜后,第二个
ComboBox
将在 XML 中显示可以使用第一个中选择的蔬菜的食谱名称ComboBox
为了做饭。
- 最后,确定
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>
C# code
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.
}
首先ComboBox
现在可以显示蔬菜名称,但我该如何制作第二个ComboBox
阅读食谱?
您的 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#中从XmlNode读取属性值? https://stackoverflow.com/questions/1600065/how-to-read-attribute-value-from-xmlnode-in-c
编辑:由于注释更正了 xml 结构。谢谢
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)