25

I would like to query an XDocument object for a given path, (e.g. "/path/to/element/I/want") but I don't know how to proceed.

Seymour
  • 7,043
  • 12
  • 44
  • 51
binncheol
  • 1,393
  • 4
  • 22
  • 38
  • possible duplicate of [how to use XPath with XDocument?](http://stackoverflow.com/questions/6209841/how-to-use-xpath-with-xdocument) – Fyodor Soikin Jun 27 '12 at 10:53
  • You can see an example selecting different paths, with / without namespace definitions, etc. here: http://stackoverflow.com/a/38272604/5838538. – Jelgab Jul 08 '16 at 20:31

4 Answers4

62

You can use methods from System.Xml.XPath.Extensions to do this.

For example, if you want to select a single element, you would use XPathSelectElement():

var element = doc.XPathSelectElement("/path/to/element/I/want");

The queries don't have to be simple paths like what you described, they use the XPath language.

svick
  • 236,525
  • 50
  • 385
  • 514
7

Even though this is a somewhat older post, it should be noted that LINQ-to-XML can be used as an alternative to System.XML.XPath to find elements based on a path within an XDocument

Example:

var results = x.Elements("path").Elements("to").Elements("element").Elements("I").Elements("want").FirstOrDefault();

Note: The LINQ to XML command may need to be altered to accommodate for the actual structure and/or cardinality of the XML.

https://msdn.microsoft.com/en-us/library/bb675156.aspx

Seymour
  • 7,043
  • 12
  • 44
  • 51
  • This makes no sense. What is x ? If x is an XContainer then Elements is an IEnumerable of XElement and you cannot chain. – user487779 Mar 15 '22 at 12:47
0

Similar to DaveDev but does work, if you do not want to use XPath.

public static class XElementExtensions
{
    public static XElement GetStrictDescendant(this XContainer element, string path)
    {
        // todo guard against null path
        var names = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
        if (names.Length == 0) 
            throw new ArgumentException("Empty path", nameof(path));

        var result = element;
        foreach (var name in names)
        {
            result = result.Element(name);
            if (result == null)
            {
                return null;
            }
        }
        return (XElement)result;
    }
}
user487779
  • 550
  • 5
  • 12
-2

Something similar to this might work:

var path = "/path/to/element/I/want";
var route = path.Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries);

XElement result = null;
foreach (var node in route)
{
    if (result == null)
    {
        result = _xmlDocument.Element(node);    
    }
    else
    {
        result = result.Element(node);
    }
}

return result;
Seymour
  • 7,043
  • 12
  • 44
  • 51
DaveDev
  • 41,155
  • 72
  • 223
  • 385