XmlWriter.WriteNode Método

Definición

Copia todo el contenido del objeto de origen en la instancia actual del sistema de escritura.

Sobrecargas

WriteNode(XmlReader, Boolean)

Cuando se invalida en una clase derivada, copia todo el contenido del lector en el sistema de escritura y desplaza el lector al inicio del siguiente nodo relacionado.

WriteNode(XPathNavigator, Boolean)

Copia todo el contenido del objeto XPathNavigator en el sistema de escritura. La posición de XPathNavigator permanece inalterada.

Comentarios

Para obtener la versión asincrónica de este método, vea WriteNodeAsync.

WriteNode(XmlReader, Boolean)

Cuando se invalida en una clase derivada, copia todo el contenido del lector en el sistema de escritura y desplaza el lector al inicio del siguiente nodo relacionado.

public:
 virtual void WriteNode(System::Xml::XmlReader ^ reader, bool defattr);
public virtual void WriteNode (System.Xml.XmlReader reader, bool defattr);
abstract member WriteNode : System.Xml.XmlReader * bool -> unit
override this.WriteNode : System.Xml.XmlReader * bool -> unit
Public Overridable Sub WriteNode (reader As XmlReader, defattr As Boolean)

Parámetros

reader
XmlReader

XmlReader desde el que se va a leer.

defattr
Boolean

Es true para copiar los atributos predeterminados de XmlReader; en caso contrario, es false.

Excepciones

reader es null.

reader contiene caracteres no válidos.

Se llamó un método XmlWriter antes de que se termine una operación asincrónica anterior. En este caso, se genera InvalidOperationException con el mensaje “Ya hay una operación asincrónica en curso”.

Ejemplos

En el ejemplo siguiente se escriben los nodos de primer y último libro en la consola.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   XmlTextReader^ reader = gcnew XmlTextReader( "books.xml" );
   reader->WhitespaceHandling = WhitespaceHandling::None;
   
   // Move the reader to the first book element.
   reader->MoveToContent();
   reader->Read();
   
   // Create a writer that outputs to the console.
   XmlTextWriter^ writer = gcnew XmlTextWriter( Console::Out );
   writer->Formatting = Formatting::Indented;
   
   // Write the start tag.
   writer->WriteStartElement( "myBooks" );
   
   // Write the first book.
   writer->WriteNode( reader, false );
   
   // Skip the second book.
   reader->Skip();
   
   // Write the last book.
   writer->WriteNode( reader, false );
   writer->WriteEndElement();
   
   // Close the writer and the reader.
   writer->Close();
   reader->Close();
}
using System;
using System.IO;
using System.Xml;

public class Sample{

  public static void Main(){

    XmlTextReader reader = new XmlTextReader("books.xml");
    reader.WhitespaceHandling = WhitespaceHandling.None;

    //Move the reader to the first book element.
    reader.MoveToContent();
    reader.Read();

    //Create a writer that outputs to the console.
    XmlTextWriter writer = new XmlTextWriter (Console.Out);
    writer.Formatting = Formatting.Indented;
    
    //Write the start tag.
    writer.WriteStartElement("myBooks");

    //Write the first book.
    writer.WriteNode(reader, false);

    //Skip the second book.
    reader.Skip();

    //Write the last book.
    writer.WriteNode(reader, false);
    writer.WriteEndElement();

    //Close the writer and the reader.
    writer.Close();
    reader.Close();
  }
}
Imports System.IO
Imports System.Xml

public class Sample

  public shared sub Main()

    Dim reader as XmlTextReader = new XmlTextReader("books.xml")
    reader.WhitespaceHandling = WhitespaceHandling.None

    'Move the reader to the first book element.
    reader.MoveToContent()
    reader.Read()

    'Create a writer that outputs to the console.
    Dim writer as XmlTextWriter = new XmlTextWriter (Console.Out)
    writer.Formatting = Formatting.Indented
    
    'Write the start tag.
    writer.WriteStartElement("myBooks")

    'Write the first book.
    writer.WriteNode(reader, false)

    'Skip the second book.
    reader.Skip()

    'Write the last book.
    writer.WriteNode(reader, false)
    writer.WriteEndElement()

    'Close the writer and the reader.
    writer.Close()
    reader.Close()

  end sub
end class

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

<bookstore>
  <book genre="autobiography" publicationdate="1981" 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" 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" ISBN="1-861001-57-6">
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>

Comentarios

En la tabla siguiente se muestran los tipos de nodo admitidos para este método.

NodeType Comportamiento de WriteNode
None Escribe todos los nodos independientemente del tipo. Es decir, el escritor consume XmlReader y escribe todos los nodos leídos, incluidos atributos, instrucciones de procesamiento, comentarios, etc.

Esta situación se produce cuando XmlReader está en un estado inicial. (La XmlReader.ReadState propiedad devuelve ReaderState.Initial).
Element Escribe el nodo de elemento y los nodos de atributo.
Attribute No hay ninguna operación. Use WriteStartAttribute o WriteAttributeString en su lugar.
Text Escribe el nodo de texto.
CDATA Escribe el nodo de la sección CDATA.
EntityReference Escribe el nodo de referencia de entidad.
ProcessingInstruction Escribe el nodo de instrucción de procesamiento.
Comment Escribe el nodo de comentario.
DocumentType Escribe el nodo de tipo de documento.
SignificantWhitespace Escribe el nodo de espacio en blanco significativo.
Whitespace Escribe el nodo de espacio en blanco.
EndElement Escribe la etiqueta de elemento final.
EndEntity No hay ninguna operación.
XmlDeclaration Escribe el nodo de declaración XML.

Si el lector está en estado inicial, este método mueve el lector al final del archivo. Si el lector ya está al final del archivo o en un estado cerrado, este método no es operativo.

El siguiente código de C# copia un documento de entrada XML completo en la consola:

XmlReader reader = XmlReader.Create(myfile);
XmlWriter writer = XmlWriter.Create(Console.Out);
writer.WriteNode(reader, false);

Si se ha movido fuera del nodo raíz y se coloca en otra parte del documento, el siguiente ejemplo de C# escribe correctamente los nodos.

XmlReader reader = XmlReader.Create(myfile);
reader.Read(); // Read PI
reader.Read(); // Read Comment
reader.Read(); // Read DOCType
XmlWriter writer = XmlWriter.Create(Console.Out);
while (!reader.EOF){
  writer.WriteNode(reader, false);
 }

Si el lector está configurado para devolver espacios en blanco y el escritor está configurado para la salida de sangría, WriteNode puede producir una salida extraña. Básicamente, obtendrá formato doble.

Para obtener la versión asincrónica de este método, vea WriteNodeAsync.

Se aplica a

WriteNode(XPathNavigator, Boolean)

Copia todo el contenido del objeto XPathNavigator en el sistema de escritura. La posición de XPathNavigator permanece inalterada.

public:
 virtual void WriteNode(System::Xml::XPath::XPathNavigator ^ navigator, bool defattr);
public virtual void WriteNode (System.Xml.XPath.XPathNavigator navigator, bool defattr);
abstract member WriteNode : System.Xml.XPath.XPathNavigator * bool -> unit
override this.WriteNode : System.Xml.XPath.XPathNavigator * bool -> unit
Public Overridable Sub WriteNode (navigator As XPathNavigator, defattr As Boolean)

Parámetros

navigator
XPathNavigator

El XPathNavigator del que se va a copiar.

defattr
Boolean

Es true para copiar los atributos predeterminados; en caso contrario, es false.

Excepciones

navigator es null.

Se llamó un método XmlWriter antes de que se termine una operación asincrónica anterior. En este caso, se genera InvalidOperationException con el mensaje “Ya hay una operación asincrónica en curso”.

Ejemplos

En el ejemplo siguiente se usa el WriteNode método para copiar el primer nodo de libro de un documento y escribirlo en la consola.

using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;

public class Sample
{

    public static void Main()
    {

        XPathDocument doc = new XPathDocument("books.xml");
        XPathNavigator nav = doc.CreateNavigator();

        // Create a writer that outputs to the console.
        XmlWriter writer = XmlWriter.Create(Console.Out);

        // Write the start tag.
        writer.WriteStartElement("myBooks");

        // Write the first book.
        nav.MoveToChild("bookstore", "");
        nav.MoveToChild("book", "");
        writer.WriteNode(nav, false);

        // Close the start tag.
        writer.WriteEndElement();

        // Close the writer.
        writer.Close();
    }
}
Imports System.IO
Imports System.Xml
Imports System.Xml.XPath

Module Module1

    Sub Main()

        Dim doc As XPathDocument = New XPathDocument("books.xml")
        Dim nav As XPathNavigator = doc.CreateNavigator()

        ' Create a writer that outputs to the console.
        Dim writer As XmlWriter = XmlWriter.Create(Console.Out)

        ' Write the start tag.
        writer.WriteStartElement("myBooks")

        ' Write the first book.
        nav.MoveToChild("bookstore", "")
        nav.MoveToChild("book", "")
        writer.WriteNode(nav, False)

        ' Close the start tag.
        writer.WriteEndElement()

        ' Close the writer.
        writer.Close()

    End Sub
End Module

En el ejemplo se usa 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>

Comentarios

En la tabla siguiente se muestran los tipos de nodo admitidos XPath para este método.

XPathNodeType Comportamiento de WriteNode
Root Escribe todos los nodos independientemente del tipo. Es decir, el escritor consume XPathNavigator y escribe todos los nodos del nodo raíz (incluidos atributos, instrucciones de procesamiento, comentarios, etc.).
Element Escribe el nodo de elemento y los nodos de atributo.
Attribute No hay ninguna operación. Use WriteStartAttribute o WriteAttributeString en su lugar.
Text Escribe el nodo de texto.
Namespace No hay ninguna operación. Use el WriteStartAttribute método o WriteAttributeString para escribir la declaración de espacio de nombres.
ProcessingInstruction Escribe el nodo de instrucción de procesamiento.
Comment Escribe el nodo de comentario.
SignificantWhitespace Escribe el nodo de espacio en blanco significativo.
Whitespace Escribe el nodo de espacio en blanco.

Para obtener la versión asincrónica de este método, vea WriteNodeAsync.

Se aplica a