Get a XElement at a given path I want to traverse a xml tree until I find the first element whose position matches the path. So if I'm looking for Foo/Bar/FooBar I want to get this:

&lt;Root&gt;
  &lt;Foo&gt;
    &lt;Bar&gt;
      &lt;FooBar /&gt; &lt;!-- This one --&gt;
    &lt;/Bar&gt;
  &lt;/Foo&gt;
&lt;/Root&gt; 


However there could be any number of &lt;FooBar /&gt;'s in my way and I only want the one at this path. I wrote 2 methods to get this:

private static XElement ElementByName(XElement parent, string name)
{
  return parent.Elements().Where(element =&gt; element.Name.LocalName == name).First();
}

private static XElement ElementAtPath(XElement root, string path)
{
  XElement target = root;
  string[] pathArr = path.Split('/');
  for (int i = 0; i &lt; pathArr.Length; i ++)
    {
      target = ElementByName(target, pathArr[i]);
    }
  return target;
}


Is there a faster / more efficient way I could achieve this?
You could try the following which utilizes XPath's XPathSelectElement extension method.

test.xml

&lt;Root&gt;
  &lt;Foo&gt;
      &lt;FooBar&gt;1&lt;/FooBar&gt;
    &lt;Bar&gt;
      &lt;FooBar&gt;2&lt;/FooBar&gt;
    &lt;/Bar&gt;
  &lt;/Foo&gt;
&lt;/Root&gt;


C#

using System;
using System.Xml.Linq;
using System.Xml.XPath;

...

    static void Main(string[] args)
    {
        XDocument document = XDocument.Load(@"test.xml");
        XElement element = ElementAtPath(document.Root, "Foo/Bar/FooBar");

        Console.WriteLine(element); // Prints &lt;FooBar&gt;2&lt;/FooBar&gt;
    }

    private static XElement ElementAtPath(XElement root, string path)
    {
        if (root == null)
        {
            throw new ArgumentNullException(nameof(root));
        }

        if (string.IsNullOrWhiteSpace(path))
        {
            throw new ArgumentException("Invalid path.");
        }

        return root.XPathSelectElement(path);
    }