Selects a list of nodes matching the XPath expression. Any prefixes found in the XPath expression are resolved using the supplied System.Xml.XmlNamespaceManager.
- xpath
- The XPath expression.
- nsmgr
- An System.Xml.XmlNamespaceManager to use for resolving namespaces for prefixes in the XPath expression.
An System.Xml.XmlNodeList containing a collection of nodes matching the XPath query.
XPath expressions can include namespaces. Namespace resolution is supported using the XmlNamespaceManager. If the XPath expression includes a prefix, the prefix and namespace URI pair must be added to the XmlNamespaceManager.
If the XPath expression does not include a prefix, it is assumed that the namespace URI is the empty namespace. If your XML includes a default namespace, you must still add a prefix and namespace URI to the XmlNamespaceManager; otherwise, you will not get any nodes selected. For more information, see Select Nodes Using XPath Navigation.
For example, if you had the following XML:
Example
<bookstore xmlns="http://www.lucernepublishing.com"> <book> <title>Pride And Prejudice</title> </book> </bookstore>
The following C# code selects all book nodes:
Example
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("ab", "http://www.lucernepublishing.com"); XmlNodeList nodelist = doc.SelectNodes("//ab:book", nsmgr);
A common issue when formulating XPath expressions is how to include a single quote (') or double quote (") in the expression. If you have to search for a value that includes a single quote, you must enclose the string in double quotes. If you need to search for a value that includes a double quote, you must enclose the string in single quotes.
For example, suppose you have the following XML:
Example
<bookstore xmlns="http://www.lucernepublishing.com"> <book> <title>'Emma'</title> </book> </bookstore>
The following Visual Basic code selects an element that contains single quotes:
Example
Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(doc.NameTable) nsmgr.AddNamespace("ab", "http://www.lucernepublishing.com") nodeList = root.SelectNodes("//ab:book[contains(ab:title,""'Emma'"")]", nsmgr)
This method is a Microsoft extension to the Document Object Model (DOM).
The System.Xml.XmlNodeList object returned by this method will be valid while the underlying document remains unchanged. If the underlying document changes, unexpected results may be returned (no exception will be thrown).