Parse XML and populate in List Box

六月ゝ 毕业季﹏ 提交于 2019-11-30 21:06:55

问题


I'm a newbie to C#.

I want to develop C# List box in Windows Form. I found this link to be helpful. But the input to the List box will be an XML of the following format:

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

The XML has to be parsed and should be populated in the list box. When particular item in the list is selected, it's CODE should be returned(i.e the value of SEL node).

Any pointers/suggestions as how to parse effectively and display in List.

The XML is coming from SAP and expecting to have around 300 to 400 records.


回答1:


You could use Linq to XML to do it like this.

XDocument xmldoc = XDocument.Load(xmlStream);
var items = (from i in xmldoc.Descendants("item")
             select new { Item = i.Element("SEL").Value, Value = i.Element("VALUE").Value }).ToList();

listBox1.DataSource = items;
listBox1.DisplayMember = "Item";
listBox1.ValueMember = "Value";



回答2:


Using Linq-to-XML, you can do this:

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

and somewhere in your code:

XDocument lbSrc = XDocument.Load("yourfile.xml");

List<item> _lbList = new List<item>();

foreach (XElement item in lbSrc.Descendants("item"))
{
   _lbList.Add(new item { CHK= item.Element("CHK").Value, 
                          SEL = Convert.ToInt32(item.Element("SEL").Value), 
                          VALUE = item.Element("VALUE").Value });
 }

and then assign that to your listbox:

lbYourListbox.DataSource = _lbList;
lbYourListbox.DisplayMember = "VALUE";
lbYourListbox.ValueMember = "SEL";

That should do it!



来源:https://stackoverflow.com/questions/2805477/parse-xml-and-populate-in-list-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!