如何读取节点中的子节点的属性

本文关键字:子节点 属性 节点 何读取 读取 | 更新日期: 2023-09-27 18:15:17

我正在尝试读取xml文件,我想这样做:

  1. 显示xml中所有蔬菜名称的ComboBox
  2. 选择蔬菜后,第二个ComboBox将在xml中显示可以使用第一个ComboBox中选择的蔬菜进行烹饪的食谱名称。
  3. 最后,使用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序列化。

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