Export (0) Print
Expand All

Extensions.XPathSelectElement Method (XNode, String, IXmlNamespaceResolver)

Selects an XElement using a XPath expression, resolving namespace prefixes using the specified IXmlNamespaceResolver.

Namespace:  System.Xml.XPath
Assembly:  System.Xml.Linq (in System.Xml.Linq.dll)

public static XElement XPathSelectElement(
	this XNode node,
	string expression,
	IXmlNamespaceResolver resolver
)

Parameters

node
Type: System.Xml.Linq.XNode

The XNode on which to evaluate the XPath expression.

expression
Type: System.String

A String that contains an XPath expression.

resolver
Type: System.Xml.IXmlNamespaceResolver

An IXmlNamespaceResolver for the namespace prefixes in the XPath expression.

Return Value

Type: System.Xml.Linq.XElement
An XElement, or null.

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type XNode. When you use instance method syntax to call this method, omit the first parameter. For more information, see Extension Methods (Visual Basic) or Extension Methods (C# Programming Guide).

You can use this method to evaluate XPath expressions that contain namespace prefixes.

The following example creates an XML tree that contains a namespace. It uses an XmlReader to read the XML document. It then gets an XmlNameTable from the XmlReader, and an XmlNamespaceManager from the XmlNameTable. It uses the XmlNamespaceManager when selecting an element.

string markup = @"
<aw:Root xmlns:aw='http://www.adventure-works.com'>
    <aw:Child1>child one data</aw:Child1>
    <aw:Child2>child two data</aw:Child2>
</aw:Root>";
XmlReader reader = XmlReader.Create(new StringReader(markup));
XElement root = XElement.Load(reader);
XmlNameTable nameTable = reader.NameTable;
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(nameTable);
namespaceManager.AddNamespace("aw", "http://www.adventure-works.com");
XElement child1 = root.XPathSelectElement("./aw:Child1", namespaceManager);
Console.WriteLine(child1);

This example produces the following output:

<aw:Child1 xmlns:aw="http://www.adventure-works.com">child one data</aw:Child1>

.NET Framework

Supported in: 4.5, 4, 3.5

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft