Search code examples
c#xmlxmlnodexmlnodelist

Navigate through XmlNode


Given this XML:

<o name="" type="product.567" id="5">
 <pl>
  <p name="product.articleNumber">413221</p>            
  <p name="product.width">2.200</p>
 </pl>
</o>
<o name="" type="product.678" id="6">
 <pl>
  <p name="product.articleNumber">1233123</p>       
  <p name="product.width">8.199</p>
 </pl>
</o>    

In a first step, I want to select all product nodes . After that, I want to iterate through the nodelist and get the articleNumber and width of each product. I don't want to select all articleNumbers right away, because I want them to be linked to the product.

I tried to generate a nodelist using

XmlDocument doc = new XmlDocument();
doc.Load("File.xml");

klvNdList = doc.SelectNodes("//o");

Now I want to get the attributes of each node by

foreach(XmlNode klv in klvNdList)
{

 XmlNode child = klv.SelectSingleNode("//p[@name='product.articleNumber']");
 string theThingIWant = child.InnerText;

}
                    

Unfortunaly it doesn't work and I only get empty texts.


Solution

  • Use newer Net XML library XML Linq that replaces the legacy Xml library

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    
    
    namespace ConsoleApplication2
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XDocument doc = XDocument.Load(FILENAME);
    
                var products = doc.Descendants("o")
                    .Select(x => new
                    {
                        name = (string)x.Attribute("name"),
                        type = (string)x.Attribute("type"),
                        id = (int)x.Attribute("id"),
                        properties = x.Descendants("p").Select(y => new { name = (string)y.Attribute("name"), value = (string)y }).ToList()
                    }).ToList();
            }
        }
      
    }