解析XML并在列表框中填充
我是C#的新手。
我想C# List box in Windows Form.
开发C# List box in Windows Form.
我发现此链接很有帮助。 但是List列表框的输入将是以下格式的XML:
00001val01 00002val02 00003val03 00004val04 00005val05
必须解析XML并应在列表框中填充。 当选择列表中的特定项时,应返回它的CODE(即SEL节点的值)。
任何有关如何有效解析并在List中显示的指针/建议。
XML来自SAP,预计将有大约300到400条记录。
您可以使用Linq to XML来执行此操作。
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";
使用Linq-to-XML,您可以这样做:
public partial class item { public object CHK { get; set; } public int SEL { get; set; } public string VALUE { get; set; } }
在你的代码中的某个地方:
XDocument lbSrc = XDocument.Load("yourfile.xml"); List- _lbList = new List
- (); 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 }); }
然后将其分配给您的列表框:
lbYourListbox.DataSource = _lbList; lbYourListbox.DisplayMember = "VALUE"; lbYourListbox.ValueMember = "SEL";
应该这样做!