Share via


XmlTextWriter.WriteStartDocument Método

Definição

Grava a declaração XML com a versão "1.0".

Sobrecargas

WriteStartDocument()

Grava a declaração XML com a versão "1.0".

WriteStartDocument(Boolean)

Grava a declaração XML com a versão “1.0” e o atributo autônomo.

Comentários

Observação

A partir do .NET Framework 2.0, recomendamos que você crie XmlWriter instâncias usando o XmlWriter.Create método e a XmlWriterSettings classe para aproveitar a nova funcionalidade.

WriteStartDocument()

Grava a declaração XML com a versão "1.0".

public:
 override void WriteStartDocument();
public override void WriteStartDocument ();
override this.WriteStartDocument : unit -> unit
Public Overrides Sub WriteStartDocument ()

Exceções

Este não é o primeiro método de gravação chamado após o construtor.

Exemplos

O exemplo a seguir grava um arquivo XML que representa um livro.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   XmlTextWriter^ writer = nullptr;
   String^ filename = "sampledata.xml";
   writer = gcnew XmlTextWriter( filename, nullptr );
   
   //Use indenting for readability.
   writer->Formatting = Formatting::Indented;
   
   //Write the XML delcaration. 
   writer->WriteStartDocument();
   
   //Write the ProcessingInstruction node.
   String^ PItext = "type='text/xsl' href='book.xsl'";
   writer->WriteProcessingInstruction( "xml-stylesheet", PItext );
   
   //Write the DocumentType node.
   writer->WriteDocType( "book", nullptr, nullptr, "<!ENTITY h 'hardcover'>" );
   
   //Write a Comment node.
   writer->WriteComment( "sample XML" );
   
   //Write a root element.
   writer->WriteStartElement( "book" );
   
   //Write the genre attribute.
   writer->WriteAttributeString( "genre", "novel" );
   
   //Write the ISBN attribute.
   writer->WriteAttributeString( "ISBN", "1-8630-014" );
   
   //Write the title.
   writer->WriteElementString( "title", "The Handmaid's Tale" );
   
   //Write the style element.
   writer->WriteStartElement( "style" );
   writer->WriteEntityRef( "h" );
   writer->WriteEndElement();
   
   //Write the price.
   writer->WriteElementString( "price", "19.95" );
   
   //Write CDATA.
   writer->WriteCData( "Prices 15% off!!" );
   
   //Write the close tag for the root element.
   writer->WriteEndElement();
   writer->WriteEndDocument();
   
   //Write the XML to file and close the writer.
   writer->Flush();
   writer->Close();
   
   //Load the file into an XmlDocument to ensure well formed XML.
   XmlDocument^ doc = gcnew XmlDocument;
   
   //Preserve white space for readability.
   doc->PreserveWhitespace = true;
   
   //Load the file.
   doc->Load( filename );
   
   //Display the XML content to the console.
   Console::Write( doc->InnerXml );
}
using System;
using System.IO;
using System.Xml;

public class Sample
{
  private const string filename = "sampledata.xml";

  public static void Main()
  {
     XmlTextWriter writer = null;

     writer = new XmlTextWriter (filename, null);
     //Use indenting for readability.
     writer.Formatting = Formatting.Indented;

     //Write the XML delcaration.
     writer.WriteStartDocument();

     //Write the ProcessingInstruction node.
     String PItext="type='text/xsl' href='book.xsl'";
     writer.WriteProcessingInstruction("xml-stylesheet", PItext);

     //Write the DocumentType node.
     writer.WriteDocType("book", null , null, "<!ENTITY h 'hardcover'>");

     //Write a Comment node.
     writer.WriteComment("sample XML");

     //Write a root element.
     writer.WriteStartElement("book");

     //Write the genre attribute.
     writer.WriteAttributeString("genre", "novel");

     //Write the ISBN attribute.
     writer.WriteAttributeString("ISBN", "1-8630-014");

     //Write the title.
     writer.WriteElementString("title", "The Handmaid's Tale");

     //Write the style element.
     writer.WriteStartElement("style");
     writer.WriteEntityRef("h");
     writer.WriteEndElement();

     //Write the price.
     writer.WriteElementString("price", "19.95");

     //Write CDATA.
     writer.WriteCData("Prices 15% off!!");

     //Write the close tag for the root element.
     writer.WriteEndElement();

     writer.WriteEndDocument();

     //Write the XML to file and close the writer.
     writer.Flush();
     writer.Close();

     //Load the file into an XmlDocument to ensure well formed XML.
     XmlDocument doc = new XmlDocument();
     //Preserve white space for readability.
     doc.PreserveWhitespace = true;
     //Load the file.
     doc.Load(filename);

     //Display the XML content to the console.
     Console.Write(doc.InnerXml);
  }
}
Option Explicit
Option Strict

Imports System.IO
Imports System.Xml

Public Class Sample
    Private Shared filename As String = "sampledata.xml"
    Public Shared Sub Main()
        Dim writer As XmlTextWriter = Nothing
        
        writer = New XmlTextWriter(filename, Nothing)
        'Use indenting for readability.
        writer.Formatting = Formatting.Indented
        
        'Write the XML delcaration. 
        writer.WriteStartDocument()
        
        'Write the ProcessingInstruction node.
        Dim PItext As String = "type='text/xsl' href='book.xsl'"
        writer.WriteProcessingInstruction("xml-stylesheet", PItext)
        
        'Write the DocumentType node.
        writer.WriteDocType("book", Nothing, Nothing, "<!ENTITY h 'hardcover'>")
        
        'Write a Comment node.
        writer.WriteComment("sample XML")
        
        'Write a root element.
        writer.WriteStartElement("book")
        
        'Write the genre attribute.
        writer.WriteAttributeString("genre", "novel")
        
        'Write the ISBN attribute.
        writer.WriteAttributeString("ISBN", "1-8630-014")
        
        'Write the title.
        writer.WriteElementString("title", "The Handmaid's Tale")
        
        'Write the style element.
        writer.WriteStartElement("style")
        writer.WriteEntityRef("h")
        writer.WriteEndElement()
        
        'Write the price.
        writer.WriteElementString("price", "19.95")
        
        'Write CDATA.
        writer.WriteCData("Prices 15% off!!")
        
        'Write the close tag for the root element.
        writer.WriteEndElement()
        
        writer.WriteEndDocument()
        
        'Write the XML to file and close the writer.
        writer.Flush()
        writer.Close()
        
        'Load the file into an XmlDocument to ensure well formed XML.
        Dim doc As New XmlDocument()
        'Preserve white space for readability.
        doc.PreserveWhitespace = True
        'Load the file.
        doc.Load(filename)
        
        'Display the XML content to the console.
        Console.Write(doc.InnerXml)
    End Sub
End Class

Comentários

Observação

A partir do .NET Framework 2.0, recomendamos que você crie XmlWriter instâncias usando o XmlWriter.Create método e a XmlWriterSettings classe para aproveitar a nova funcionalidade.

O nível de codificação do documento é determinado pela forma como o gravador é implementado. Por exemplo, se um Encoding objeto for especificado no XmlTextWriter construtor, isso determinará o valor do atributo de codificação. Esse método não cria um atributo autônomo.

Quando WriteStartDocument é chamado, o gravador valida que o que você está escrevendo é um documento XML bem formado. Por exemplo, ele verifica se a declaração XML é o primeiro nó, que um e apenas um elemento de nível raiz existe e assim por diante. Se esse método não for chamado, o gravador pressupõe que um fragmento XML esteja sendo gravado e não aplicará nenhuma regra de nível raiz.

Se WriteStartDocument tiver sido chamado e, em seguida, o WriteProcessingInstruction método for usado para criar outra declaração XML, uma exceção será gerada.

Aplica-se a

WriteStartDocument(Boolean)

Grava a declaração XML com a versão “1.0” e o atributo autônomo.

public:
 override void WriteStartDocument(bool standalone);
public override void WriteStartDocument (bool standalone);
override this.WriteStartDocument : bool -> unit
Public Overrides Sub WriteStartDocument (standalone As Boolean)

Parâmetros

standalone
Boolean

Se true, grava "standalone=yes"; se false, ele grava "standalone=no".

Exceções

Este não é o primeiro método de gravação chamado após o construtor.

Comentários

Observação

A partir do .NET Framework 2.0, recomendamos que você crie XmlWriter instâncias usando o XmlWriter.Create método e a XmlWriterSettings classe para aproveitar a nova funcionalidade.

O nível de codificação do documento é determinado pela forma como o gravador é implementado. Por exemplo, se um Encoding objeto for especificado no XmlTextWriter construtor, isso determinará o valor do atributo de codificação.

Quando WriteStartDocument é chamado, o gravador valida que o que você está escrevendo é um documento XML bem formado. Por exemplo, ele verifica se a declaração XML é o primeiro nó, se um e apenas um elemento de nível raiz existe e assim por diante. Se esse método não for chamado, o gravador pressupõe que um fragmento XML esteja sendo gravado e não aplicará nenhuma regra de nível raiz.

Se WriteStartDocument tiver sido chamado e, em seguida, o WriteProcessingInstruction método for usado para criar outra declaração XML, uma exceção será gerada.

Aplica-se a