XmlWriter.WriteNode Método

Definição

Copia tudo desde o objeto de origem para a instância do escritor atual.

Sobrecargas

Name Description
WriteNode(XmlReader, Boolean)

Quando sobreposto numa classe derivada, copia tudo do leitor ao escritor e move o leitor para o início do irmão seguinte.

WriteNode(XPathNavigator, Boolean)

Copia tudo, desde o XPathNavigator objeto até ao escritor. A posição do XPathNavigator grupo mantém-se inalterada.

Observações

Para a versão assíncrona deste método, veja WriteNodeAsync.

WriteNode(XmlReader, Boolean)

Origem:
XmlWriter.cs
Origem:
XmlWriter.cs
Origem:
XmlWriter.cs
Origem:
XmlWriter.cs
Origem:
XmlWriter.cs

Quando sobreposto numa classe derivada, copia tudo do leitor ao escritor e move o leitor para o início do irmão seguinte.

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

A XmlReader leitura.

defattr
Boolean

true para copiar os atributos padrão do XmlReader; caso contrário, false.

Exceções

reader é null.

reader contém caracteres inválidos.

Um XmlWriter método era chamado antes de uma operação assíncrona anterior terminar. Neste caso, InvalidOperationException é lançado com a mensagem "Uma operação assíncrona já está em curso."

Exemplos

O exemplo seguinte escreve o primeiro e o último nós do livro para a consola.

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

Observações

A tabela seguinte mostra os tipos de nós suportados para este método.

NodeType Comportamento do WriteNode
None Escreve todos os nós independentemente do tipo. Ou seja, o autor consome e XmlReader escreve todos os nós lidos, incluindo atributos, instruções de processamento, comentários, e assim por diante.

Esta situação ocorre quando o XmlReader está num estado inicial. (A XmlReader.ReadState propriedade devolve ReaderState.Initial).
Element Escreve o nó elemento e quaisquer nós de atributo.
Attribute Nenhuma operação em curso. Use WriteStartAttribute ou WriteAttributeString em vez disso.
Text Escreve o nó de texto.
CDATA Escreve o nó da secção CDATA.
EntityReference Escreve o nó de referência da entidade.
ProcessingInstruction Escreve o nó de instruções de processamento.
Comment Escreve o nó de comentário.
DocumentType Escreve o nó do tipo de documento.
SignificantWhitespace Escreve o nó de espaço em branco significativo.
Whitespace Escreve o nó de espaço em branco.
EndElement Escreve a etiqueta do elemento final.
EndEntity Nenhuma operação em curso.
XmlDeclaration Escreve o nó de declaração XML.

Se o leitor estiver no estado inicial, este método move o leitor para o final do ficheiro. Se o leitor já estiver no final do ficheiro ou em estado fechado, este método é não operacional.

O seguinte código C# copia um documento de entrada XML completo para a consola:

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

Se já saíste do nó raiz e estiveres posicionado noutro local do documento, o exemplo seguinte em C# escreve corretamente os nós.

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 devolver espaço em branco e o escritor estiver configurado para indentar a saída, WriteNode pode produzir uma saída estranha. Essencialmente, vais receber formatação dupla.

Para a versão assíncrona deste método, veja WriteNodeAsync.

Aplica-se a

WriteNode(XPathNavigator, Boolean)

Origem:
XmlWriter.cs
Origem:
XmlWriter.cs
Origem:
XmlWriter.cs
Origem:
XmlWriter.cs
Origem:
XmlWriter.cs

Copia tudo, desde o XPathNavigator objeto até ao escritor. A posição do XPathNavigator grupo mantém-se 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

O XPathNavigator para copiar.

defattr
Boolean

true copiar os atributos padrão; caso contrário, false.

Exceções

navigator é null.

Um XmlWriter método era chamado antes de uma operação assíncrona anterior terminar. Neste caso, InvalidOperationException é lançado com a mensagem "Uma operação assíncrona já está em curso."

Exemplos

O exemplo seguinte utiliza o WriteNode método para copiar o primeiro nó livro de um documento e escrevê-lo para a 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

O exemplo usa o ficheiro 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>

Observações

A tabela seguinte mostra os tipos de nós suportados XPath para este método.

XPathNodeType Comportamento do WriteNode
Root Escreve todos os nós independentemente do tipo. Ou seja, o autor consome e XPathNavigator escreve todos os nós do nó raiz (incluindo atributos, instruções de processamento, comentários e assim por diante).
Element Escreve o nó elemento e quaisquer nós de atributo.
Attribute Nenhuma operação em curso. Use WriteStartAttribute ou WriteAttributeString em vez disso.
Text Escreve o nó de texto.
Namespace Nenhuma operação em curso. Use o WriteStartAttribute método ou WriteAttributeString para escrever a declaração de namespace.
ProcessingInstruction Escreve o nó de instruções de processamento.
Comment Escreve o nó de comentário.
SignificantWhitespace Escreve o nó de espaço em branco significativo.
Whitespace Escreve o nó de espaço em branco.

Para a versão assíncrona deste método, veja WriteNodeAsync.

Aplica-se a