C# 如何使用XLinq读取XML并将其绑定到组合框?
您好,我正在尝试使用XLinq读取XML文件,并将值绑定到组合框中:-C# 如何使用XLinq读取XML并将其绑定到组合框?,c#,xml,winforms,linq-to-xml,C#,Xml,Winforms,Linq To Xml,您好,我正在尝试使用XLinq读取XML文件,并将值绑定到组合框中:- XDocument xmlDoc = XDocument.Load("abc.xml"); var res = from c in xmlDoc.Element("Clients").Descendants("Client") select c; cmb1.BindingContext = new BindingContext(); cmb1.DataSource = res; cmb1.D
XDocument xmlDoc = XDocument.Load("abc.xml");
var res = from c in xmlDoc.Element("Clients").Descendants("Client")
select c;
cmb1.BindingContext = new BindingContext();
cmb1.DataSource = res;
cmb1.DisplayMember = "Name";
cmb1.ValueMember = "ID";
我的XMl结构如下所示:-
<Clients>
<Client>
<ID>-1</ID>
<Name>--Select--</Name>
</Client>
<Client>
<ID>1</ID>
<Name>A</Name>
</Client>
<Client>
<ID>2</ID>
<Name>B</Name>
</Client>
<Client>
<ID>3</ID>
<Name>C</Name>
</Client>
<Client>
<ID>4</ID>
<Name>D</Name>
</Client>
</Clients>
您当前的查询生成一个
IEnumerable
,它没有提供您想要的属性
// not tested
var res = from c in xmlDoc.Element("Clients").Descendants("Client")
select new { Name=c.Element("Name").Value, ID = c.Element("ID").Value };
...
cmb1.DataSource = res.ToList();
ID将是一个字符串 什么错误?请把这行的详细内容写下来。我不想在“XMl结构是这样的”这个问题上花太多时间。@Henk:谢谢,但听起来XMl结构不好。请向我推荐正确的结构,因为它是可变的。@Henk:同时更新我的问题(添加错误详细信息)现在我更想知道正确的XML格式。(正如你在上面的评论中提到的)谢谢。其工作原理如下:但是你喜欢什么样的XML格式呢?我的评论不是关于你的格式,而是关于一个问题中的“类似的东西”。哦。对不起,亨克。谢谢你
// not tested
var res = from c in xmlDoc.Element("Clients").Descendants("Client")
select new { Name=c.Element("Name").Value, ID = c.Element("ID").Value };
...
cmb1.DataSource = res.ToList();