解析XML并在List Box中填充

时间:2010-05-11 04:38:01

标签: c# .net xml listbox xml-parsing

我发布了同样的问题here,我也有很多好的答案。当我尝试相同的答案时,我遇到了编译错误。后来我知道我们正在使用.NET 2.0,而我们现有的应用程序没有引用LINQ文件。

SO中搜索后,我试图找出部分内容:

public partial class Item
    {
        public object CHK { get; set; }
        public int SEL { get; set; }
        public string VALUE { get; set; }
    }

解析:

        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<LISTBOX_ST>
             <item><CHK></CHK><SEL>00001</SEL><VALUE>val01</VALUE></item>
             <item><CHK></CHK><SEL>00002</SEL><VALUE>val02</VALUE></item>
             <item><CHK></CHK><SEL>00003</SEL><VALUE>val03</VALUE></item>
             <item><CHK></CHK><SEL>00004</SEL><VALUE>val04</VALUE></item>
             <item><CHK></CHK><SEL>00005</SEL><VALUE>val05</VALUE></item>
                   </LISTBOX_ST>");            
       List<Item> _lbList = new List<Item>();
       foreach (XmlNode node in doc.DocumentElement.ChildNodes)
        {
            string text = node.InnerText; //or loop through its children as well
            //HOW - TO - POPULATE THE ITEM OBJECT ??????
        }
       listBox1.DataSource = _lbList;
       listBox1.DisplayMember = "VALUE";
       listBox1.ValueMember = "SEL";

如何读取两个子节点 - 节点的SEL和VALUE并在新的DTO中填充相同的节点?

1 个答案:

答案 0 :(得分:2)

你可以这样做:

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(@"<LISTBOX_ST>
     <item><CHK></CHK><SEL>00001</SEL><VALUE>val01</VALUE></item>
     <item><CHK></CHK><SEL>00002</SEL><VALUE>val02</VALUE></item>
     <item><CHK></CHK><SEL>00003</SEL><VALUE>val03</VALUE></item>
     <item><CHK></CHK><SEL>00004</SEL><VALUE>val04</VALUE></item>
     <item><CHK></CHK><SEL>00005</SEL><VALUE>val05</VALUE></item>
     </LISTBOX_ST>");            

    List<Item> _lbList = new List<Item>();
   foreach (XmlNode node in doc.DocumentElement.ChildNodes)
    {
        string chk = node.ChildNodes[0].InnerText;
        int sel = int.Parse(node.ChildNodes[1].InnerText);
        string value = node.ChildNodes[2].InnerText;

        Item item = new Item();
        item.CHK = chk;
        item.VALUE = value;
        item.SEL = sel;

        _lbList.Add(item);
    }
   listBox1.DataSource = _lbList;
   listBox1.DisplayMember = "VALUE";
   listBox1.ValueMember = "SEL";