0

I have this XML file and I want to fill my list with only article id and item_description value.

<?xml version="1.0" encoding="utf-8"?>
<articles>
  <article id="i1">
    <item_description>Mobitel Smasung</item_description>
    <single_price>Kom</single_price>
    <unit_of_measure>1250</unit_of_measure>
  </article>
    <article id="i2">
    <item_description>Mobitel DA</item_description>
    <single_price>WD</single_price>
    <unit_of_measure>232</unit_of_measure>
  </article>
</articles>

This is what I got so far:

        public void LoadAllArticles()
        {
            XDocument xdoc = XDocument.Load(defaultDataPath + @"\saved_articles.xml");

            foreach (var article in xdoc.XPathSelectElements("articles/article"))
            {
                articles = article.Descendants()
                               .Select(element => element.Value)
                               .ToList();

            }
        }

How to load only id + " " + item_description to the list?

1 Answers1

0

Since you want the id attribute from the parent article, move the call to Descendants() into the Select() lamdba to perform the string concatenation (skip the foreach loop):

    articles = xdoc.XPathSelectElements("articles/article")
                   .Select(art => art.Attribute("id").Value + " " + art.Descendants().FirstOrDefault(node => node.Name == "item_description", "<no description>"))
                   .ToList();
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206