Compartir a través de


Extracción de datos XML mediante XPathNavigator

Hay varias maneras diferentes de representar un documento XML en Microsoft .NET Framework. Esto incluye el uso de String, o mediante las clases XmlReader, XmlWriter, XmlDocument o XPathDocument. Para facilitar el movimiento entre estas diferentes representaciones de un documento XML, la XPathNavigator clase proporciona una serie de métodos y propiedades para extraer el XML como un Stringobjeto , XmlReader un objeto o XmlWriter un objeto .

Convertir un XPathNavigator en una cadena

La OuterXml propiedad de la XPathNavigator clase se usa para obtener el marcado de todo el documento XML o simplemente el marcado de un solo nodo y sus nodos secundarios.

Nota:

La propiedad InnerXml obtiene solamente el marcado de los nodos secundarios de un nodo.

En el ejemplo de código siguiente se muestra cómo guardar un documento XML completo contenido en un XPathNavigator objeto como String, así como un nodo único y sus nodos secundarios.

Dim document As XPathDocument = New XPathDocument("input.xml")  
Dim navigator As XPathNavigator = document.CreateNavigator()  
  
' Save the entire input.xml document to a string.  
Dim xml As String = navigator.OuterXml  
  
' Now save the Root element and its child nodes to a string.  
navigator.MoveToChild(XPathNodeType.Element)  
Dim root As String = navigator.OuterXml  
XPathDocument document = new XPathDocument("input.xml");  
XPathNavigator navigator = document.CreateNavigator();  
  
// Save the entire input.xml document to a string.  
string xml = navigator.OuterXml;  
  
// Now save the Root element and its child nodes to a string.  
navigator.MoveToChild(XPathNodeType.Element);  
string root = navigator.OuterXml;  

Convertir un XPathNavigator en xmlReader

El ReadSubtree método se usa para transmitir todo el contenido de un documento XML o simplemente un solo nodo y sus nodos secundarios a un XmlReader objeto .

Cuando el XmlReader objeto se crea con el nodo actual y sus nodos secundarios, la XmlReader propiedad del ReadState objeto se establece en Initial. XmlReader Cuando se llama al método del objeto Read por primera vez, XmlReader se mueve al nodo actual de XPathNavigator. El nuevo XmlReader objeto continúa leyendo hasta que se alcanza el final del árbol XML. En este punto, el Read método devuelve false y la XmlReader propiedad del ReadState objeto se establece en EndOfFile.

La XPathNavigator posición del objeto no cambia por la creación o el movimiento del XmlReader objeto. El ReadSubtree método solo es válido cuando se coloca en un elemento o nodo raíz.

En el ejemplo siguiente se muestra cómo obtener un XmlReader objeto que contiene todo el documento XML en un XPathDocument objeto, así como un solo nodo y sus nodos secundarios.

Dim document As XPathDocument = New XPathDocument("books.xml")  
Dim navigator As XPathNavigator = document.CreateNavigator()  
  
' Stream the entire XML document to the XmlReader.  
Dim xml As XmlReader = navigator.ReadSubtree()  
  
While xml.Read()  
    Console.WriteLine(xml.ReadInnerXml())  
End While  
  
xml.Close()  
  
' Stream the book element and its child nodes to the XmlReader.  
navigator.MoveToChild("bookstore", "")  
navigator.MoveToChild("book", "")  
  
Dim book As XmlReader = navigator.ReadSubtree()  
  
While book.Read()  
    Console.WriteLine(book.ReadInnerXml())  
End While  
  
book.Close()  
XPathDocument document = new XPathDocument("books.xml");  
XPathNavigator navigator = document.CreateNavigator();  
  
// Stream the entire XML document to the XmlReader.  
XmlReader xml = navigator.ReadSubtree();  
  
while (xml.Read())  
{  
    Console.WriteLine(xml.ReadInnerXml());  
}  
  
xml.Close();  
  
// Stream the book element and its child nodes to the XmlReader.  
navigator.MoveToChild("bookstore", "");  
navigator.MoveToChild("book", "");  
  
XmlReader book = navigator.ReadSubtree();  
  
while (book.Read())  
{  
    Console.WriteLine(book.ReadInnerXml());  
}  
  
book.Close();  

En el ejemplo se toma el archivo books.xml como entrada.

<?xml version="1.0" encoding="utf-8" ?> 
<bookstore>
    <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
        <title>The Autobiography of Benjamin Franklin</title>
        <author>
            <first-name>Benjamin</first-name>
            <last-name>Franklin</last-name>
        </author>
        <price>8.99</price>
    </book>
    <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
        <title>The Confidence Man</title>
        <author>
            <first-name>Herman</first-name>
            <last-name>Melville</last-name>
        </author>
        <price>11.99</price>
    </book>
    <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
        <title>The Gorgias</title>
        <author>
            <name>Plato</name>
        </author>
        <price>9.99</price>
    </book>
</bookstore>

Conversión de un XPathNavigator en xmlWriter

El WriteSubtree método se usa para transmitir todo el contenido de un documento XML o simplemente un solo nodo y sus nodos secundarios a un XmlWriter objeto .

La XPathNavigator posición del objeto no cambia por la creación del XmlWriter objeto.

En el ejemplo siguiente se muestra cómo obtener un XmlWriter objeto que contiene todo el documento XML en un XPathDocument objeto, así como un solo nodo y sus nodos secundarios.

Dim document As XPathDocument = New XPathDocument("books.xml")  
Dim navigator As XPathNavigator = document.CreateNavigator()  
  
' Stream the entire XML document to the XmlWriter.  
Dim xml As XmlWriter = XmlWriter.Create("newbooks.xml")  
navigator.WriteSubtree(xml)  
xml.Close()  
  
' Stream the book element and its child nodes to the XmlWriter.  
navigator.MoveToChild("bookstore", "")  
navigator.MoveToChild("book", "")  
  
Dim book As XmlWriter = XmlWriter.Create("book.xml")  
navigator.WriteSubtree(book)  
book.Close()  
XPathDocument document = new XPathDocument("books.xml");  
XPathNavigator navigator = document.CreateNavigator();  
  
// Stream the entire XML document to the XmlWriter.  
XmlWriter xml = XmlWriter.Create("newbooks.xml");  
navigator.WriteSubtree(xml);  
xml.Close();  
  
// Stream the book element and its child nodes to the XmlWriter.  
navigator.MoveToChild("bookstore", "");  
navigator.MoveToChild("book", "");  
  
XmlWriter book = XmlWriter.Create("book.xml");  
navigator.WriteSubtree(book);  
book.Close();  

En el ejemplo se toma el books.xml archivo encontrado anteriormente en este tema como entrada.

Consulte también