This is my Xml file:
<?xml version="1.0" encoding="utf-8" ?>
<dati>
<product id="456">
<item>a</item>
<item>b</item>
<item>c</item>
</product>
<product id="789">
<item>a</item>
<item>b</item>
</product>
<product id="533">
<item>a</item>
</product>
</dati>
Code below returns only first item.InnerText element
List<string> lst = new List<string>();
XDocument Doc = XDocument.Load("test.xml");
var q = from c in Doc.Descendants("product")
where c.Attribute("id").Value == "789"
select c.Element("item");
foreach (string name in q)
lst.Add(name);
listBox1.DataSource = lst;
how can I have a collection of all items for selected product?
Sure:
Note that this takes a slightly different approach – it checks that there’s exactly one matching product element (by finding it) and then selects the
itemelements underneath it, projecting each to its value. It then converts those strings into a list in a rather neater way 🙂