XmlNode.SelectSingleNode Método

Definición

Selecciona el primer XmlNode que coincide con la expresión XPath.

Sobrecargas

SelectSingleNode(String)

Selecciona el primer XmlNode que coincide con la expresión XPath.

SelectSingleNode(String, XmlNamespaceManager)

Selecciona el primer XmlNode que coincide con la expresión XPath. Los prefijos encontrados en la expresión XPath se resuelven utilizando el XmlNamespaceManager proporcionado.

Ejemplos

En el ejemplo siguiente se devuelve el primer libro con el nombre del autor coincidente. XmlNamespaceManager resuelve el espacio de nombres predeterminado en la expresión XPath.

#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;
}
using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main()
  {

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

      // Create an XmlNamespaceManager to resolve the default namespace.
      XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
      nsmgr.AddNamespace("bk", "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("descendant::bk:book[bk:author/bk:last-name='Atwood']", nsmgr);

      Console.WriteLine(book.OuterXml);
  }
}
Imports System.IO
Imports System.Xml

Public Class Sample

  Public Shared Sub Main()

      Dim doc As XmlDocument = New XmlDocument()
      doc.Load("newbooks.xml")

      'Create an XmlNamespaceManager for resolving namespaces.
      Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(doc.NameTable)
      nsmgr.AddNamespace("bk", "urn:newbooks-schema")

      'Select the book written by an author whose last name is Atwood.
      Dim book As XmlNode 
      Dim root As XmlElement = doc.DocumentElement
      book = root.SelectSingleNode("descendant::bk:book[bk:author/bk:last-name='Atwood']", nsmgr)

      Console.WriteLine(book.OuterXml)

  End Sub
End Class

En el ejemplo se usa el archivo , newbooks.xmlcomo entrada.

<?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>

Comentarios

Las expresiones XPath pueden incluir espacios de nombres. La resolución de espacios de nombres es compatible con XmlNamespaceManager. Si la expresión XPath incluye un prefijo, el par de URI de prefijo y espacio de nombres se debe agregar a XmlNamespaceManager.

Nota

Si la expresión XPath no incluye un prefijo, se supone que el URI del espacio de nombres es el espacio de nombres vacío. Si el XML incluye un espacio de nombres predeterminado, debe agregar un prefijo y un URI de espacio de nombres a XmlNamespaceManager; de lo contrario, no obtendrá ningún nodo seleccionado. Para obtener más información, vea Seleccionar nodos mediante la navegación XPath.

SelectSingleNode(String)

Selecciona el primer XmlNode que coincide con la expresión XPath.

public:
 System::Xml::XmlNode ^ SelectSingleNode(System::String ^ xpath);
public System.Xml.XmlNode? SelectSingleNode (string xpath);
public System.Xml.XmlNode SelectSingleNode (string xpath);
member this.SelectSingleNode : string -> System.Xml.XmlNode
Public Function SelectSingleNode (xpath As String) As XmlNode

Parámetros

xpath
String

Expresión XPath. Vea ejemplos de XPath.

Devoluciones

Primer XmlNode que coincide con la consulta XPath o null si no se encuentra un nodo coincidente.

Excepciones

La expresión XPath contiene un prefijo.

Ejemplos

En el ejemplo siguiente se cambia el precio del primer libro de Jane Austen.

#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 );
}
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);
  }
}
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

En el ejemplo se usa el archivo , booksort.xmlcomo entrada.


<?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>

Comentarios

Si la expresión XPath requiere resolución de espacio de nombres, debe usar la SelectSingleNode sobrecarga que toma un XmlNamespaceManager como argumento. XmlNamespaceManager se usa para resolver espacios de nombres.

Nota

Si la expresión XPath no incluye un prefijo, se supone que el URI del espacio de nombres es el espacio de nombres vacío. Si el XML incluye un espacio de nombres predeterminado, debe seguir usando XmlNamespaceManager y agregarle un prefijo y un URI de espacio de nombres; de lo contrario, no obtendrá un nodo seleccionado. Para obtener más información, vea Seleccionar nodos mediante la navegación XPath.

Nota

Un problema común al formular expresiones XPath es cómo incluir una comilla simple (') o comilla doble (") en la expresión. Si tiene que buscar un valor que incluya una comilla simple, debe incluir la cadena entre comillas dobles. Si necesita buscar un valor que incluya una comilla doble, debe incluir la cadena entre comillas simples.

Por ejemplo, supongamos que tiene el siguiente XML:

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

El siguiente código de Visual Basic selecciona un elemento que contiene comillas simples:

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

Este método es una extensión Microsoft al Modelo de objetos de documento (DOM).

Consulte también

Se aplica a

SelectSingleNode(String, XmlNamespaceManager)

Selecciona el primer XmlNode que coincide con la expresión XPath. Los prefijos encontrados en la expresión XPath se resuelven utilizando el XmlNamespaceManager proporcionado.

public:
 System::Xml::XmlNode ^ SelectSingleNode(System::String ^ xpath, System::Xml::XmlNamespaceManager ^ nsmgr);
public System.Xml.XmlNode? SelectSingleNode (string xpath, System.Xml.XmlNamespaceManager nsmgr);
public System.Xml.XmlNode SelectSingleNode (string xpath, System.Xml.XmlNamespaceManager nsmgr);
member this.SelectSingleNode : string * System.Xml.XmlNamespaceManager -> System.Xml.XmlNode
Public Function SelectSingleNode (xpath As String, nsmgr As XmlNamespaceManager) As XmlNode

Parámetros

xpath
String

Expresión XPath. Vea ejemplos de XPath.

nsmgr
XmlNamespaceManager

XmlNamespaceManager que se utiliza para resolver los espacios de nombres de los prefijos de la expresión XPath.

Devoluciones

Primer XmlNode que coincide con la consulta XPath o null si no se encuentra un nodo coincidente.

Excepciones

La expresión XPath contiene un prefijo que no está definido en XmlNamespaceManager.

Ejemplos

En el ejemplo siguiente se selecciona el libro con el valor ISBN coincidente.

#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" );
   
   //Create an XmlNamespaceManager for resolving namespaces.
   XmlNamespaceManager^ nsmgr = gcnew XmlNamespaceManager( doc->NameTable );
   nsmgr->AddNamespace( "bk", "urn:samples" );
   
   //Select the book node with the matching attribute value.
   XmlNode^ book;
   XmlElement^ root = doc->DocumentElement;
   book = root->SelectSingleNode( "descendant::book->Item[@bk:ISBN='1-861001-57-6']", nsmgr );
   Console::WriteLine( book->OuterXml );
}
using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main()
  {

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

      //Create an XmlNamespaceManager for resolving namespaces.
      XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
      nsmgr.AddNamespace("bk", "urn:samples");

      //Select the book node with the matching attribute value.
      XmlNode book;
      XmlElement root = doc.DocumentElement;
      book = root.SelectSingleNode("descendant::book[@bk:ISBN='1-861001-57-6']", nsmgr);

      Console.WriteLine(book.OuterXml);
  }
}
Imports System.IO
Imports System.Xml

public class Sample

  public shared sub Main()

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

      'Create an XmlNamespaceManager for resolving namespaces.
      Dim nsmgr as XmlNamespaceManager = new XmlNamespaceManager(doc.NameTable)
      nsmgr.AddNamespace("bk", "urn:samples")

      'Select the book node with the matching attribute value.
      Dim book as XmlNode 
      Dim root as XmlElement = doc.DocumentElement
      book = root.SelectSingleNode("descendant::book[@bk:ISBN='1-861001-57-6']", nsmgr)

      Console.WriteLine(book.OuterXml)

  end sub
end class

En el ejemplo se usa el archivo , booksort.xmlcomo entrada.


<?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>

Comentarios

Las expresiones XPath pueden incluir espacios de nombres. La resolución de espacios de nombres es compatible con XmlNamespaceManager. Si la expresión XPath incluye un prefijo, el par de URI de prefijo y espacio de nombres se debe agregar a XmlNamespaceManager.

Nota

Si la expresión XPath no incluye un prefijo, se supone que el URI del espacio de nombres es el espacio de nombres vacío. Si el XML incluye un espacio de nombres predeterminado, debe agregar un prefijo y un URI de espacio de nombres a XmlNamespaceManager; de lo contrario, no obtendrá un nodo seleccionado. Para obtener más información, vea Seleccionar nodos mediante la navegación XPath.

Por ejemplo, si tenía el siguiente CÓDIGO XML:

<bookstore xmlns="http://www.lucernepublishing.com">
 <book>
   <title>Pride And Prejudice</title>
 </book>
</bookstore>

El código de C# siguiente selecciona el primer nodo de libro:

XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ab", "http://www.lucernepublishing.com");
XmlNode book = doc.SelectSingleNode("//ab:book", nsmgr);

Nota

Un problema común al formular expresiones XPath es cómo incluir una comilla simple (') o comilla doble (") en la expresión. Si tiene que buscar un valor que incluya una comilla simple, debe incluir la cadena entre comillas dobles. Si necesita buscar un valor que incluya una comilla doble, debe incluir la cadena entre comillas simples.

Por ejemplo, supongamos que tiene el siguiente XML:

<bookstore xmlns="http://www.lucernepublishing.com">
  <book>
    <title>&apos;Emma&apos;</title>
  </book>
</bookstore>

El siguiente código de Visual Basic selecciona un elemento que contiene comillas simples:

Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(doc.NameTable)
nsmgr.AddNamespace("ab", "http://www.lucernepublishing.com")
book = root.SelectSingleNode("descendant::ab:book[ab:title=""'Emma'""]", nsmgr)

Este método es una extensión Microsoft al Modelo de objetos de documento (DOM).

Consulte también

Se aplica a