Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a list of xml element from Descendants

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?

like image 284
Barbara Avatar asked May 11 '12 13:05

Barbara


People also ask

What is a descendant in an XML document?

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 ].

What is the difference between XDocument and XmlDocument?

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 .

What is an XML child element?

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.

What is LINQ to XML?

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.


1 Answers

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 :)

like image 72
Jon Skeet Avatar answered Sep 20 '22 13:09

Jon Skeet