XmlWriter.Close 方法

定義

當在衍生類別中覆寫時,會關閉此串流及底層串流。

public:
 virtual void Close();
public:
 abstract void Close();
public virtual void Close();
public abstract void Close();
abstract member Close : unit -> unit
override this.Close : unit -> unit
abstract member Close : unit -> unit
Public Overridable Sub Close ()
Public MustOverride Sub Close ()

例外狀況

在被呼叫後 Close ,會呼叫更多輸出,或該呼叫的結果是無效的 XML 文件。

-或-

在先前非同步操作結束前,會呼叫一個 XmlWriter 方法。 此時, InvalidOperationException 會拋出「非同步操作已進行中」的訊息。

範例

以下範例撰寫一個 XML 節點。

using System;
using System.IO;
using System.Xml;

public class Sample {

  public static void Main() {

     // Create a writer to write XML to the console.
     XmlWriterSettings settings = new XmlWriterSettings();
     settings.Indent = true;
     settings.OmitXmlDeclaration = true;
     XmlWriter writer = XmlWriter.Create(Console.Out, settings);

     // Write the book element.
     writer.WriteStartElement("book");

     // Write the title element.
     writer.WriteStartElement("title");
     writer.WriteString("Pride And Prejudice");
     writer.WriteEndElement();

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

     // Write the XML and close the writer.
     writer.Close();
  }
}
Option Explicit
Option Strict

Imports System.IO
Imports System.Xml

Public Class Sample
    
  Public Shared Sub Main()

     ' Create a writer to write XML to the console.
     Dim settings As XmlWriterSettings = new XmlWriterSettings()
     settings.Indent = true
     settings.OmitXmlDeclaration = true
     Dim writer As XmlWriter = XmlWriter.Create(Console.Out, settings)

     ' Write the book element.
     writer.WriteStartElement("book")
        
     ' Write the title element.
     writer.WriteStartElement("title")
     writer.WriteString("Pride And Prejudice")
     writer.WriteEndElement()
        
     ' Write the close tag for the root element.
     writer.WriteEndElement()
        
     ' Write the XML and close the writer.
     writer.Close()

  End Sub
End Class

備註

任何未開啟的元素或屬性都會自動關閉。

Note

當你使用 XmlWriter 方法輸出 XML 時,元素和屬性不會被寫入,直到你呼叫該 Close 方法。 例如,如果你使用 XmlWriter 來填充一個 XmlDocument,直到關閉 XmlWriter,你將無法觀察目標文件中的寫入元素和屬性。

適用於