我想从XML文件中获取一些值,并使用LINQ将它们插入到ListBox中。我错在哪里?用LINQ解析XML问题
<?xml version="1.0" encoding="UTF-8"?>
<tells>
<defindividual name="name1"/>
<instanceof>
<individual name="name1"/>
<catom name="value"/>
</instanceof>
<defindividual name="name2"/>
<instanceof>
<individual name="name2"/>
<catom name="value"/>
</instanceof>
<defindividual name="name3"/>
<instanceof>
<individual name="name3"/>
<catom name="otherValue"/>
</instanceof>
</tells>
代码隐藏:
protected void Button1_Click(object sender, EventArgs e)
{
XDocument owlXML = XDocument.Load(Server.MapPath("App_Data\\myFile.xml"));
var items = from item in owlXML.Descendants("instanceof")
where item.Element("catom").Attribute("name").Value == "value"
select new
{
catom = item.Element("catom").Attribute("name").Value
};
foreach (var item in items)
{
//ListBox1.DataSource = item;
//ListBox1.DataBind();
ListBox1.Items.Add(item.catom);
}
}
而not_工作什么_does? – abatishchev 2011-05-31 14:42:26
问题是我的ListBox1始终是空的。我试图用List <>项填充它,它工作,但是当我尝试用IEnumerable项填充它时,没有任何反应。 – nyxz 2011-05-31 14:54:44
我更新了添加'ToArray()'的答案。您也可以使用ToList(),但不需要产生的开销。 – abatishchev 2011-05-31 15:02:28