XmlNode::SelectSingleNode Method
Selects the first XmlNode that matches the XPath expression.
Assembly: System.Xml (in System.Xml.dll)
| Name | Description | |
|---|---|---|
![]() | SelectSingleNode(String^) | Selects the first XmlNode that matches the XPath expression. |
![]() | SelectSingleNode(String^, XmlNamespaceManager^) | Selects the first XmlNode that matches the XPath expression. Any prefixes found in the XPath expression are resolved using the supplied XmlNamespaceManager. |
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.
Note |
|---|
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. |
The following example returns the first book with the matching author name. The XmlNamespaceManager resolves the default namespace in the XPath expression.
#using <System.Xml.dll> using namespace System; using namespace System::IO; using namespace System::Xml; int main() { XmlDocument^ doc = gcnew XmlDocument; doc->Load( L"newbooks.xml" ); // Create an XmlNamespaceManager to resolve the default namespace. XmlNamespaceManager^ nsmgr = gcnew XmlNamespaceManager( doc->NameTable ); nsmgr->AddNamespace( L"bk", L"urn:newbooks-schema" ); // Select the first book written by an author whose last name is Atwood. XmlNode^ book; XmlElement^ root = doc->DocumentElement; book = root->SelectSingleNode( L"descendant::bk:book[bk:author/bk:last-name='Atwood']", nsmgr ); Console::WriteLine( book->OuterXml ); return 0; }
The example uses the file, newbooks.xml, as input.
<?xml version='1.0'?> <bookstore xmlns="urn:newbooks-schema"> <book genre="novel" style="hardcover"> <title>The Handmaid's Tale</title> <author> <first-name>Margaret</first-name> <last-name>Atwood</last-name> </author> <price>19.95</price> </book> <book genre="novel" style="other"> <title>The Poisonwood Bible</title> <author> <first-name>Barbara</first-name> <last-name>Kingsolver</last-name> </author> <price>11.99</price> </book> </bookstore>

