.NET Framework Class Library
XmlNode..::.SelectSingleNode Method (String)

Selects the first XmlNode that matches the XPath expression.

Namespace:  System.Xml
Assembly:  System.Xml (in System.Xml.dll)
Syntax

Visual Basic (Declaration)
Public Function SelectSingleNode ( _
    xpath As String _
) As XmlNode
Visual Basic (Usage)
Dim instance As XmlNode
Dim xpath As String
Dim returnValue As XmlNode

returnValue = instance.SelectSingleNode(xpath)
C#
public XmlNode SelectSingleNode(
    string xpath
)
Visual C++
public:
XmlNode^ SelectSingleNode(
    String^ xpath
)
JScript
public function SelectSingleNode(
    xpath : String
) : XmlNode

Parameters

xpath
Type: System..::.String
The XPath expression.

Return Value

Type: System.Xml..::.XmlNode
The first XmlNode that matches the XPath query or nullNothingnullptra null reference (Nothing in Visual Basic) if no matching node is found. The XmlNode should not be expected to be connected "live" to the XML document. That is, changes that appear in the XML document may not appear in the XmlNode, and vice versa.
Exceptions

ExceptionCondition
XPathException

The XPath expression contains a prefix.

Remarks

If the XPath expression requires namespace resolution, you must use the SelectSingleNode overload which takes an XmlNamespaceManager as its argument. The XmlNamespaceManager is used to resolve namespaces.

NoteNote:

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 use the XmlNamespaceManager and add a prefix and namespace URI to it; otherwise, you will not get a selected node. For more information, see Select Nodes Using XPath Navigation.

NoteNote:

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:

 <bookstore>
   <book>
     <title>&apos;Emma&apos;</title>
   </book>
 </bookstore>

The following Visual Basic code selects an element that contains single quotes:

 book = root.SelectSingleNode("descendant::book[title=""'Emma'""]")

This method is a Microsoft extension to the Document Object Model (DOM).

Examples

The following example changes the price of the first Jane Austen book.

Visual Basic
Imports System
Imports System.IO
Imports System.Xml

public class Sample

  public shared sub Main()

    'Create the XmlDocument.
    Dim doc as XmlDocument = new XmlDocument()
    doc.Load("booksort.xml")

    Dim book as XmlNode
    Dim root as XmlNode = doc.DocumentElement

    book=root.SelectSingleNode("descendant::book[author/last-name='Austen']")

    'Change the price on the book.
    book.LastChild.InnerText="15.95"

    Console.WriteLine("Display the modified XML document....")
    doc.Save(Console.Out)

  end sub
end class
C#
using System;
using System.IO;
using System.Xml;

public class Sample {

  public static void Main() {

    XmlDocument doc = new XmlDocument();
    doc.Load("booksort.xml");

    XmlNode book;
    XmlNode root = doc.DocumentElement;

    book=root.SelectSingleNode("descendant::book[author/last-name='Austen']");

    //Change the price on the book.
    book.LastChild.InnerText="15.95";

    Console.WriteLine("Display the modified XML document....");
    doc.Save(Console.Out);    
  }
}
Visual C++
#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   XmlDocument^ doc = gcnew XmlDocument;
   doc->Load( "booksort.xml" );
   XmlNode^ book;
   XmlNode^ root = doc->DocumentElement;
   book = root->SelectSingleNode( "descendant::book[author/last-name='Austen']" );

   //Change the price on the book.
   book->LastChild->InnerText = "15.95";
   Console::WriteLine( "Display the modified XML document...." );
   doc->Save( Console::Out );
}

CPP_OLD
#using <mscorlib.dll>
#using <System.Xml.dll>
using namespace System;
using namespace System::IO;
using namespace System::Xml;

int main()
{
    XmlDocument* doc = new XmlDocument();
    doc->Load(S"booksort.xml");

    XmlNode* book;
    XmlNode* root = doc->DocumentElement;

    book=root->SelectSingleNode(S"descendant::book[author/last-name='Austen']");

    //Change the price on the book.
    book->LastChild->InnerText=S"15.95";

    Console::WriteLine(S"Display the modified XML document....");
    doc->Save(Console::Out);    
}

The example uses the file, booksort.xml, as input.

None
<?xml version="1.0"?>
<!-- A fragment of a book store inventory database -->
<bookstore xmlns:bk="urn:samples">
  <book genre="novel" publicationdate="1997" bk:ISBN="1-861001-57-8">
    <title>Pride And Prejudice</title>
    <author>
      <first-name>Jane</first-name>
      <last-name>Austen</last-name>
    </author>
    <price>24.95</price>
  </book>
  <book genre="novel" publicationdate="1992" bk:ISBN="1-861002-30-1">
    <title>The Handmaid's Tale</title>
    <author>
      <first-name>Margaret</first-name>
      <last-name>Atwood</last-name>
    </author>
    <price>29.95</price>
  </book>
  <book genre="novel" publicationdate="1991" bk:ISBN="1-861001-57-6">
    <title>Emma</title>
    <author>
      <first-name>Jane</first-name>
      <last-name>Austen</last-name>
    </author>
    <price>19.95</price>
  </book>
  <book genre="novel" publicationdate="1982" bk:ISBN="1-861001-45-3">
    <title>Sense and Sensibility</title>
    <author>
      <first-name>Jane</first-name>
      <last-name>Austen</last-name>
    </author>
    <price>19.95</price>
  </book>
</bookstore>
Platforms

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0

XNA Framework

Supported in: 3.0, 2.0, 1.0
See Also

Reference

Tags :


Community Content

Sean Kellt - MSFT
SelectSingleNode can be used to update nodes in an XML document.

The guidance under return value is confusing.

The XmlNode should not be expected to be connected "live" to the XML document. That is, changes that appear in the XML document may not appear in the XmlNode, and vice versa.

This makes it seem as though using SelectSingleNode is a read-only operation in that changes made to the resulting node will not be reflected back into the XML document. Consider the following XML

 
 <books>
   <book>
     <title>The Hitchiker's Guide</title>
   </book>
 </books>
 

It is perfectly legal and expected that you could use the following code to correct the title.

  XmlDocument xml = new XmlDocument();
 
  xml.Load(@"C:\library.xml");
  
  XmlNode node = sessionXml.DocumentElement.SelectSingleNode"/library/book/title");
if (node != null)
node.InnerText = "The Hitchhiker's Guide to the Galaxy";
  


Reading the article titled Select Nodes Using XPath Navigation (http://msdn2.microsoft.com/en-us/library/d271ytdx.aspx) we see a similar but different warning.

When the underlying document is modified, it is advisable to rerun the select. If the node modified is one that could cause the node to be added to the node list when it was not previously, or would now cause it to be removed from the node list, there is no guarantee that the node list is now accurate.

So what this means is that updates to the node returned by SelectSingleNode will make it back into the XML document. However, if the XML document changes the node may no longer point to the node that would satisfy the XPath query. For example, say we add another book element to the beginning of the xml file like so

 <books>
   <book>
     <title>The Lord of the Rings</title>
   </book>
   <book>
     <title>The Hitchiker's Guide</title>
   </book>
 </books>

Our node would now point to the second book in the list. If we called SelectSingleNode again as in the sample above, we would get the first book instead of the second.

Tags :

Jack Burnish
This will not work for Sharepoint Web Service returns

Traditional XPath will not work against nodes returned via a Sharepoint Webservice unless you use the (string,Namespacemanager) method and declare a namespace before using local names in a query

For example

Dim GroupName As XmlNode = xmlDoc.SelectSingleNode("/child::node()/child::node()/child::node()") 


Will return the first child Group from the following

<GetGroupCollectionFromSitexmlns="http://schemas.microsoft.com/sharepoint/soap/directory/">
    <Groups>
        <GroupID="3804"Name="GroupName"Description="GroupSelection"OwnerID="1"OwnerIsUser="True" />
    </Groups>
</GetGroupCollectionFromSite>



This returns nothing

Dim GroupName As XmlNode = xmlDoc.SelectSingleNode("/GetGroupCollectionFromSite/Groups/Group")


until you add the namespacemanager and import the node into an xmldocument

Dim xmlDoc As XmlDocument = New XmlDocument()
Dim xmlGroupList As XmlNode = Users.GetGroupCollectionFromSite()
xmlDoc.LoadXml(xmlGroupList.OuterXml)
Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(xmlDoc.NameTable)
nsmgr.AddNamespace("ab", "http://schemas.microsoft.com/sharepoint/soap/directory/")
Dim GroupName As XmlNode = xmlDoc.SelectSingleNode("/ab:GetGroupCollectionFromSite/ab:Groups/ab:Group[@ID='3804']", nsmgr)

Returns the Group Node with the ID of 3804

Hopefully this will save some other XML/XPath newbies some debugging time
SPD automatically adds a Namespace to your queries without having to do the above.


Page view tracker