解析XML并填充列表框列表、XML

2023-09-03 08:11:53 作者:三朝元老i

我是一个新手,C#。

I'm a newbie to C#.

我想开发 C#列表框的Windows窗体。我发现这链接是有帮助的。 但输入到列表框中将下列格式的XML:

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>

的XML有要分析并应该填充在列表框。当列表中的特定项目被选中,这是code应返还(即SEL节点的值)。

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.

XML是SAP的到来,期待有大约300至400条记录。

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

推荐答案

您可以使用LINQ到XML做这样的。

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