我想从XML文件中获取一些值,并使用LINQ将它们插入到ListBox中。我哪里错了?
<?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);
}
}
var names = from item in owlXML.Descendants("instanceof")
let name = item.Element("catom").Attribute("name") // cache
where name.Value == "value"
select name;
foreach (var name in names.ToArray())
{
ListBox1.Items.Add(name);
}
或
var items = from item in owlXML.Descendants("instanceof")
let name = item.Element("catom").Attribute("name") // cache
where name.Value == "value"
select new { catom = name }; // if ListBox is configured to field="catom"
ListBox1.DataSource = items.ToArray(); // items!
ListBox1.DataBind();