tags:

views:

851

answers:

3

I'm trying to learn some Linq to XML stuff, and I came across the XPathSelectElement function in XElement. This function seems to do just what I need, but for some reason, I can't use it! Check out my code:

        XElement rootElement = XElement.Load(dataFile);
        XElement parentElement = rootElement.XPathSelectElement(xPath);

I have included references to System.Xml.Linq everywhere that is needed. All the other stuff in that library that I have tried appears to be working, but XPathSelectElement doesn't even appear in the Intellisense in visual studio.

When building the above code, I get the following error:

Error 1 'System.Xml.Linq.XElement' does not contain a definition for 'XPathSelectElement' and no extension method 'XPathSelectElement' accepting a first argument of type 'System.Xml.Linq.XElement' could be found (are you missing a using directive or an assembly reference?) C:\PageHelpControl\PageHelp.cs 155 50 HelpControl

+5  A: 

The methods you are trying to use are extension menthods. You need to include System.Xml.XPath namespace.

Micah
A: 

According to MSDN it is not a single argument method, but instead a two or three argument method under the System.Xml.XPath.Extensions namespace. The signatures are:

XPathSelectElement(XNode, String)
XPathSelectElement(XNode, String, IXmlNamespaceResolver)
Gavin Miller
It's an extension method - with the right using directive it can be used as if it were an instance method *on* XNode.
Jon Skeet
+1  A: 

Just to tie the two answers together...

XPathSelectElement is an extension method. To use it as an extension method (i.e. as if it were an instance method on XNode) you need to have a using directive in your source code for the relevant namespace:

using System.Xml.XPath;

(That's where the Extensions class which contains the extension method lives.)

This works in the same way that you need using System.Linq; in your code before you can use Select, Where etc on IEnumerable<T>.

Jon Skeet