XmlTextWriter.WriteStartDocument Метод

Определение

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

Перегрузки

Имя Описание
WriteStartDocument()

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

WriteStartDocument(Boolean)

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

Комментарии

Note

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

WriteStartDocument()

Исходный код:
XmlTextWriter.cs
Исходный код:
XmlTextWriter.cs
Исходный код:
XmlTextWriter.cs
Исходный код:
XmlTextWriter.cs
Исходный код:
XmlTextWriter.cs

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

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

Исключения

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

Примеры

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

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

Комментарии

Note

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

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

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

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

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

WriteStartDocument(Boolean)

Исходный код:
XmlTextWriter.cs
Исходный код:
XmlTextWriter.cs
Исходный код:
XmlTextWriter.cs
Исходный код:
XmlTextWriter.cs
Исходный код:
XmlTextWriter.cs

Записывает 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"; if false, он записывает "standalone=no".

Исключения

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

Комментарии

Note

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

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

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

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

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