XmlTextWriter.WriteStartDocument Метод

Определение

Записывает объявление XML с номером версии "1.0".

Перегрузки

WriteStartDocument()

Записывает объявление XML с номером версии "1.0".

WriteStartDocument(Boolean)

Записывает объявление XML с номером версии "1.0" и отдельным атрибутом.

Комментарии

Примечание

Начиная с версии платформа .NET Framework 2.0 рекомендуется создавать XmlWriter экземпляры с помощью XmlWriter.Create метода и XmlWriterSettings класса, чтобы воспользоваться преимуществами новых функциональных возможностей.

WriteStartDocument()

Записывает объявление XML с номером версии "1.0".

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

Исключения

Это не первый метод записи, вызываемый после конструктора.

Примеры

В следующем примере записывается XML-файл, представляющий книгу.

#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

Комментарии

Примечание

Начиная с версии платформа .NET Framework 2.0 рекомендуется создавать XmlWriter экземпляры с помощью XmlWriter.Create метода и XmlWriterSettings класса, чтобы воспользоваться преимуществами новых функциональных возможностей.

Уровень кодирования документа определяется способом реализации модуля записи. Например, если Encoding объект указан в конструкторе XmlTextWriter , это определяет значение атрибута кодирования. Этот метод не создает автономный атрибут.

При WriteStartDocument вызове модуля записи проверяет, является ли запись хорошо сформированным XML-документом. Например, он проверяет, что объявление XML является первым узлом, существует ли только один и только один элемент корневого уровня и т. д. Если этот метод не вызывается, модуль записи предполагает, что фрагмент XML записывается и не применяет правила корневого уровня.

Если WriteStartDocument был вызван, а затем WriteProcessingInstruction метод используется для создания другого XML-объявления, возникает исключение.

Применяется к

WriteStartDocument(Boolean)

Записывает объявление XML с номером версии "1.0" и отдельным атрибутом.

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

Параметры

standalone
Boolean

Если значение равно true, записывается "standalone=yes"; если false, записывается "standalone=no".

Исключения

Это не первый метод записи, вызываемый после конструктора.

Комментарии

Примечание

Начиная с версии платформа .NET Framework 2.0 рекомендуется создавать XmlWriter экземпляры с помощью XmlWriter.Create метода и XmlWriterSettings класса, чтобы воспользоваться преимуществами новых функциональных возможностей.

Уровень кодирования документа определяется способом реализации модуля записи. Например, если Encoding объект указан в конструкторе XmlTextWriter , это определяет значение атрибута кодирования.

При WriteStartDocument вызове модуля записи проверяет, является ли запись хорошо сформированным XML-документом. Например, он проверяет, что объявление XML является первым узлом, существует ли только один и только один элемент корневого уровня и т. д. Если этот метод не вызывается, модуль записи предполагает, что фрагмент XML записывается и не применяет правила корневого уровня.

Если WriteStartDocument был вызван, а затем WriteProcessingInstruction метод используется для создания другого XML-объявления, возникает исключение.

Применяется к