XmlWriter.WriteNode Método

Definição

Copia tudo do objeto de origem para a instância atual do gravador.Copies everything from the source object to the current writer instance.

Sobrecargas

WriteNode(XmlReader, Boolean)

Quando substituído em uma classe derivada, copia tudo do leitor no gravador e move o leitor para o início do próximo irmão.When overridden in a derived class, copies everything from the reader to the writer and moves the reader to the start of the next sibling.

WriteNode(XPathNavigator, Boolean)

Copia tudo do objeto XPathNavigator no gravador.Copies everything from the XPathNavigator object to the writer. A posição do XPathNavigator permanece inalterada.The position of the XPathNavigator remains unchanged.

Comentários

Para obter a versão assíncrona desse método, consulte WriteNodeAsync .For the asynchronous version of this method, see WriteNodeAsync.

WriteNode(XmlReader, Boolean)

Quando substituído em uma classe derivada, copia tudo do leitor no gravador e move o leitor para o início do próximo irmão.When overridden in a derived class, copies everything from the reader to the writer and moves the reader to the start of the next sibling.

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

O XmlReader para leitura.The XmlReader to read from.

defattr
Boolean

true para copiar os atributos padrão do XmlReader; caso contrário, false.true to copy the default attributes from the XmlReader; otherwise, false.

Exceções

reader é null.reader is null.

reader contém caracteres inválidos.reader contains invalid characters.

Um método XmlWriter foi chamado antes do término de uma operação assíncrona anterior.An XmlWriter method was called before a previous asynchronous operation finished. Nesse caso, InvalidOperationException será gerado com a mensagem “Uma operação assíncrona já está em andamento”.In this case, InvalidOperationException is thrown with the message "An asynchronous operation is already in progress."

Exemplos

O exemplo a seguir grava o primeiro e o último nós do livro no console.The following example writes the first and last book nodes out to the console.

#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

O exemplo usa o arquivo, books.xml , como entrada.The example uses the file, books.xml, as input.

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

Comentários

A tabela a seguir mostra os tipos de nó com suporte para esse método.The following table shows the supported node types for this method.

NodeTypeNodeType Comportamento de WriteNodeWriteNode Behavior
None Grava todos os nós, independentemente do tipo.Writes out all the nodes irrespective of type. Ou seja, o gravador consome o XmlReader e grava todos os nós lidos, incluindo atributos, instruções de processamento, comentários e assim por diante.That is, the writer consumes the XmlReader and writes out all the nodes read including attributes, processing instructions, comments, and so on.

Essa situação ocorre quando o XmlReader está em um estado inicial.This situation occurs when the XmlReader is in an initial state. (A XmlReader.ReadState propriedade retorna ReaderState.Initial ).(The XmlReader.ReadState property returns ReaderState.Initial).
Element Grava o nó do elemento e todos os nós de atributo.Writes out the element node and any attribute nodes.
Attribute Sem operação.No operation. Use WriteStartAttribute ou WriteAttributeString em vez disso.Use WriteStartAttribute or WriteAttributeString instead.
Text Remove o nó de texto.Writes out the text node.
CDATA remove o nó da seção CDATA.Writes out the CDATA section node.
EntityReference Grava o nó de referência de entidade.Writes out the entity reference node.
ProcessingInstruction Grava o nó de instrução de processamento.Writes out the processing instruction node.
Comment Grava o nó de comentário.Writes out the comment node.
DocumentType Grava o nó do tipo de documento.Writes out the document type node.
SignificantWhitespace Grava o nó de espaço em branco significativo.Writes out the significant white space node.
Whitespace Grava o nó de espaço em branco.Writes out the white space node.
EndElement Grava a marca do elemento final.Writes out the end element tag.
EndEntity Sem operação.No operation.
XmlDeclaration Grava o nó de declaração XML.Writes out the XML declaration node.

Se o leitor estiver no estado inicial, esse método moverá o leitor para o final do arquivo.If the reader is in the initial state, this method moves the reader to the end of file. Se o leitor já estiver no final do arquivo ou em um estado fechado, esse método não será operacional.If the reader is already at the end of file or in a closed state, this method is non-operational.

O código C# a seguir copia um documento de entrada XML inteiro para o console:The following C# code copies an entire XML input document to the console:

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

Se você tiver movido para fora do nó raiz e estiver posicionado em outro lugar no documento, o exemplo C# a seguir gravará os nós corretamente.If you have moved off the root node and are positioned elsewhere in the document the following C# example correctly writes out the nodes.

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

Se o leitor estiver configurado para retornar espaço em branco e o gravador tiver sido configurado para recuar a saída, o WriteNode poderá produzir uma saída estranha.If the reader is configured to return white space and the writer has is configured to indent output, WriteNode may produce strange output. Essencialmente, você estará obtendo formatação dupla.You will essentially be getting double formatting.

Para obter a versão assíncrona desse método, consulte WriteNodeAsync .For the asynchronous version of this method, see WriteNodeAsync.

Aplica-se a

WriteNode(XPathNavigator, Boolean)

Copia tudo do objeto XPathNavigator no gravador.Copies everything from the XPathNavigator object to the writer. A posição do XPathNavigator permanece inalterada.The position of the XPathNavigator remains unchanged.

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

O XPathNavigator do qual copiar.The XPathNavigator to copy from.

defattr
Boolean

true para copiar os atributos padrão; caso contrário, false.true to copy the default attributes; otherwise, false.

Exceções

navigator é null.navigator is null.

Um método XmlWriter foi chamado antes do término de uma operação assíncrona anterior.An XmlWriter method was called before a previous asynchronous operation finished. Nesse caso, InvalidOperationException será gerado com a mensagem “Uma operação assíncrona já está em andamento”.In this case, InvalidOperationException is thrown with the message "An asynchronous operation is already in progress."

Exemplos

O exemplo a seguir usa o WriteNode método para copiar o primeiro nó de livro de um documento e gravá-lo no console do.The following example uses the WriteNode method to copy the first book node from a document and write it to the console.

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

O exemplo usa o arquivo de books.xml como entrada.The example uses the books.xml file as input.

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

Comentários

A tabela a seguir mostra os XPath tipos de nó com suporte para esse método.The following table shows the supported XPath node types for this method.

XPathNodeTypeXPathNodeType Comportamento de WriteNodeWriteNode Behavior
Root Grava todos os nós, independentemente do tipo.Writes out all the nodes irrespective of type. Ou seja, o gravador consome o XPathNavigator e grava todos os nós do nó raiz (incluindo atributos, instruções de processamento, comentários e assim por diante).That is, the writer consumes the XPathNavigator and writes out all the nodes from the root node (including attributes, processing instructions, comments and so on.)
Element Grava o nó do elemento e todos os nós de atributo.Writes out the element node and any attribute nodes.
Attribute Sem operação.No operation. Use WriteStartAttribute ou WriteAttributeString em vez disso.Use WriteStartAttribute or WriteAttributeString instead.
Text Remove o nó de texto.Writes out the text node.
Namespace Sem operação.No operation. Use o WriteStartAttribute WriteAttributeString método ou para gravar a declaração de namespace.Use the WriteStartAttribute or WriteAttributeString method to write the namespace declaration.
ProcessingInstruction Grava o nó de instrução de processamento.Writes out the processing instruction node.
Comment Grava o nó de comentário.Writes out the comment node.
SignificantWhitespace Grava o nó de espaço em branco significativo.Writes out the significant white space node.
Whitespace Grava o nó de espaço em branco.Writes out the white space node.

Para obter a versão assíncrona desse método, consulte WriteNodeAsync .For the asynchronous version of this method, see WriteNodeAsync.

Aplica-se a