24

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
  • 6,964
  • 12
  • 42
  • 48
binncheol
  • 1,331
  • 3
  • 20
  • 37
  • 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

5 Answers5

60

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
  • 225,720
  • 49
  • 378
  • 501
5

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
  • 6,964
  • 12
  • 42
  • 48
  • 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

I needed to do something similar. This repo has several unit tests demoing XDocument querying with XPathEvaluate()

jchristof
  • 2,682
  • 6
  • 28
  • 45
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
  • 492
  • 4
  • 11
-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
  • 6,964
  • 12
  • 42
  • 48
DaveDev
  • 39,517
  • 70
  • 210
  • 376