如何读取节点中的子节点的属性
本文关键字:子节点 属性 节点 何读取 读取 | 更新日期: 2023-09-27 18:15:17
我正在尝试读取xml文件,我想这样做:
- 显示xml中所有蔬菜名称的
ComboBox
。 - 选择蔬菜后,第二个
ComboBox
将在xml中显示可以使用第一个ComboBox
中选择的蔬菜进行烹饪的食谱名称。 - 最后,使用OK按钮,所选配方将读取指向该配方的文件路径。
<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文件读取食谱呢?
您可以构建以下Xpath,然后获取蔬菜的配方
string xpath = string.Format("//vegetable[@name='{0}']/recipe",comboboxSelectedItem);
var selectedVegetableRecipe = xdoc.SelectSingleNode(xpath);
但是,正如Ondrej Tucny指出的那样,在应用程序启动期间,您可以将xml文档缓存在静态XMLDocument中,然后在代码中使用它来避免每次调用的性能开销。
首先,您没有将解析后的XML存储在任何地方。因此在comboBox1_SelectedIndexChanged
你不能用它工作。您应该在表单中引入私有字段(或属性,无论什么),而不是xDoc
局部变量。
如果出于某种奇怪的原因想要继续使用现在处理XML文件的方式,则必须在comboBox1_SelectedIndexChanged
中查找选定的<vegetable>
元素,然后处理其所有子<recipe>
元素。然而,这是不必要的复杂。更好的方法是从声明数据结构开始,并使用XML序列化。
Vegetable
和Recipe
,并使用XmlSerializer
来序列化(存储到XML中)和反序列化(从XML中读取)您的数据。在表单中,您将使用对象,而不必手动处理XML。