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

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

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

我写的XML

    C:\\   D:\\     E:\\   F:\\    

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. } 

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

您的xml应该重新构建,因为在将配方名称和文件路径节点作为配方节点的值时混合数据

这是一个更好的方法:

    C:\\   D:\\     E:\\   F:\\    

因此,要显示配方,您需要提取配方节点的属性。 这里解释了如何做到这一点: 如何从C#中的XmlNode读取属性值?

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

如果您希望能够从文档中获取蔬菜的名称,最简单的方法是将其定义为自己独立的数据。 关于你所做的事情并没有什么无效 ,但它使得获得你想要的数据变得非常困难。

如果可以,可以将结构更改为类似的内容,这样可以让您的生活更轻松:

   Carrot  ABCrecipe C:\\   DEFrecipe D:\\    

假设您使用的是.NET 3.5或更高版本,您将可以访问LINQ-to-XML API。 这些提供了一种从XML文档中读取值的简化方法,并且应该可以更轻松地解决此问题。

您使用以下方法创建文档:

 var document = XDocument.Load("Recipe_List.xml"); 

然后你可以编写一个查询来获取这样的蔬菜元素:

 var vegetables = document .Element(XName.Get("vegetables")) .Elements(XName.Get("vegetable")); 

一旦你有了这些元素,就可以获得他们的名字,如下所示:

 var vegNames = vegetables.Select(ele => ele.Element(XName.Get("name")).Value); 

然后,您可以非常轻松地将此信息插入到combobox中:

 foreach (string name in vegNames) { comboBox1.Items.Add(name); } 

我假设你在.Net 4.0框架中使用C#

你可以像这样格式化你的xml:

   Carrot  ABCrecipe C:\\   DEFrecipe D:\\    Potato  CBArecipe E:\\   FEDrecipe F:\\    

然后只需使用此查询来选择这些项:

 var vegiesList = (from veg in xDoc.Descendants("vegetable") select new Vegetable() { Name = veg.Element("name").Value, Recipes = (from re in veg.Elements("recipe") select new Recipe(re.Element("name").Value, re.Element("FilePath").Value)).ToList() }) .ToList(); 

然后为你的class级结构:

 class Vegetable { public string Name { get; set; } public List Recipes { get; set; } } class Recipe { public Recipe(string name, string path) { Name = name; Path = path; } public string Name { get; set; } public string Path { get; set; } } vegiesList.ForEach(veg => comboBox1.Items.Add(veg.Name)); //You can select its property here depending on what property you want to add on your `ComboBox`