My Technical Notes

Friday, 8 February 2013

Using XPathSelectElements for XDocument

XDocument seems to lack versions of XmlDocument.SelectSingleNode and XmlDocument.SelectsNodes where we pass xpath string. e.g.

provide an example...

Instead we can use XPathSelectElement and XPathSelectElements extension methods which can be found in the System.Xml.XPath namespace:


using System;
using System.Xml.Linq;
using System.Xml.XPath; // for XPathSelectElements

namespace testconsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument xdoc = XDocument.Parse(
                @"<root>
                    <child>
                        <name>john</name>
                    </child>
                    <child>
                        <name>fred</name>
                    </child>
                    <child>
                        <name>mark</name>
                    </child>
                 </root>");

            foreach (var childElem in xdoc.XPathSelectElements("//child"))
            {
                string childName = childElem.Element("name").Value;
                Console.WriteLine(childName);
            }
        }
    }
}
In the above code it may be better to use the Descendents:

foreach (var childElem in xdoc.Descendants("child"))
{
   string childName = childElem.Element("name").Value;
   Console.WriteLine(childName);
}

No comments: