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?
A descendant node of any node A is any node below A in a tree model, where "below" means "away from the root." document element. There is only one document element in a Document . This element node is a child of the Document node. See Well-Formed XML Documents in XML [ XML 1.0 ].
XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument .
An element can either be defined globally i.e. as a child of the <xs:schema>, or locally within a compositor (<xs:all>, <xs:choice>, <xs:sequence>). A globally defined <xs:element> can be used as the root element within an XML document, and can also be re-used within the schema.
LINQ to XML is a LINQ-enabled, in-memory XML programming interface that enables you to work with XML from within the . NET programming languages. LINQ to XML is like the Document Object Model (DOM) in that it brings the XML document into memory.
Sure:
var list = Doc.Descendants("product")
.Single(c => c.Attribute("id").Value == "789")
.Elements("item")
.Select(item => (string) item)
.ToList();
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 item
elements underneath it, projecting each to its value. It then converts those strings into a list in a rather neater way :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With