在C#中的XmlReader中从XML填充组合框

时间:2014-09-10 07:51:46

标签: c# xml combobox xmlreader

我必须阅读XML并在C#中填充组合框。这是我试过的:

private class Item 
{
  public string Name;
  public int Id

  public Item(string name, int id) 
  {
      Name = name; 
      Id = id;
  }
}   

这是我的XmlReader代码:

if (reader.IsStartElement())
{
    //return only when you have START tag
    switch (reader.Name.ToString())
    {
        case "Ad_Ref":
            Console.WriteLine("Name of the Element is : " + reader.ReadString());
            break;

        case "Ad_Id":
            Console.WriteLine("Your Id is : " + reader.ReadString());
            break;
    }
}

我如何做到这一点comboBox1.Items.Add(new Item("Student 1", 1));

我的XML只有两个标签,一个是Ad_Id,另一个是Ad_Ref

更新:这是XML Sample

<Listings>
 <Listing>
  <Ad_Id>1</Ad_Id>
 <Ad_Ref>admin</Ad_Ref>
  </Listing>
 </Listings>

1 个答案:

答案 0 :(得分:1)

如果您选择XmlReader,则可以执行以下操作:

XmlReader.ReadToFollowing用于读取兄弟元素节点。

var lstItems = new List<Item>();
using(XmlReader reader = XmlReader.Create("test.xml"))
{
    while (reader.Read())
    {
        if (reader.NodeType == XmlNodeType.Element)

            if (reader.Name == "Ad_Id")
            {
                reader.Read();
                string sAd_ID = reader.Value;
                string sAd_Ref = string.Empty;

                if (reader.ReadToFollowing("Ad_Ref"))
                {
                     reader.Read();
                     sAd_Ref = reader.Value;
                }

                 if(!string.IsNullOrEmpty(sAd_ID) && sAd_Ref != string.Empty)                        
                     lstItems.Add(new Item(sAd_Ref, Convert.ToInt32(sAd_ID)));
            }
     }
 }

您可以将List<Item>填充为上面的lstItems并将其与ComboBox绑定。

comboBox1.DataSource = lstItems;
comboBox1.DisplayMember="Name";
comboBox1.ValueMember="Id";    

<强>更新

将类的访问修饰符更改为public并添加属性gettersetter

public class Item
{
    public string Name { get; set; }
    public int Id { get; set; }

    public Item(string name, int id)
    {
        Name = name;
        Id = id;
    }
}