...">

Getting a list of xml elements 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>

The code below returns only the first element. 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 collect all the items for the selected product?

+3
source share
1 answer

Of course:

var list = Doc.Descendants("product")
              .Single(c => c.Attribute("id").Value == "789")
              .Elements("item")
              .Select(item => (string) item)
              .ToList();

Note that this requires a slightly different approach - it checks that there is only one corresponding product element (by searching for it), and then selects the elements itembelow it, projecting each of its values. Then it converts these lines to a list pretty neatly :)

+7
source

All Articles