共用方式為


以 XmlTextWriter 建立格式正確的 XML

XmlTextWriter 衍生自 XmlWriter,它會將 XML 寫至檔案、主控台 (Console)、資料流和其他的輸出類型。撰寫 XML 時,這些方法會執行額外的工作來產生格式正確的 XML。下表提供方法清單,這些方法為您執行了確保資料為格式正確的工作。

方法

完成工作的說明

WriteAttributeString

XmlTextWriter 依據它所找到的來逸出屬性的文字內容。

WriteString

XmlTextWriter 會逸出特殊字元,必要時以 & < > 和數字字元實體取代它們。

WriteBase64

XmlTextWriter 對 base64 位元組編碼,之後可使用 XmlReader 上的 ReadBinary 來讀取它。

下列的其他工作由 XmlTextWriter 完成,以確保格式正確的 XML:

  • 確保 XML 項目依正確的順序寫出。例如,它不會允許您在項目外寫入屬性、在屬性內寫入 CDATA 區塊或寫入多個根項目 (Root Element)。除此之外,它確保 <?xml declaration comes first and that the <!DOCTYPE 節點會出現在根項目之前。

  • 請確保 xml:space 屬性的值和格式正確無誤,並依據<全球資訊網協會 (W3C) 可延伸標記語言 (XML) 1.0 (第四版)>(英文) 建議事項來確定其值可接受。下列範例顯示如何在 WriteAttributeString 方法中使用 xml:space 的有效值:

    w.WriteAttributeString("xml:space", "", "preserve");
    

    xml:space 屬性的有效值包括 defaultpreserve。如果引數不是這些值的其中之一,將擲回 ArgumentException

  • 檢查字串何時會當做參數使用 (例如 Null==String.Empty 和 String.Empty),以及它是否遵循 W3C 規則。

下表列出由 XmlTextWriter 定義、而並非繼承自或定義於 XmlWriter 中或者繼承自 Object 的其他方法與屬性。

方法或屬性

說明

XmlTextWriter

建立 XmlTextWriter 的執行個體,此執行個體會採用檔名、資料流或 TextWriter。存在一個多載方法,以接受定義編碼類型的其他參數。

Namespace 屬性

指定是否支援命名空間。當這個屬性設定為 false 時,不會寫入 xmlns 宣告,您可以指定包含不限冒號數目的項目名稱。

Formatting 屬性

定義是否使用縮排來格式化輸出。

IndentChar 屬性

定義在執行縮排 Formatting 時,用來縮排的字元。

Indentation 屬性

定義在執行縮排 Formatting 時,階層中的每一個層級所寫入的 IndentChars 數量。

QuoteChar 屬性

定義用來對屬性值加上引號的字元。這必須是單引號 &#39; 或雙引號 &#34;

BaseStream

傳回 XmlTextWriter 寫入的資料流。如果 XmlTextWriter 是使用非衍生自 StreamWriterTextWriter 所建構的,則傳回 Null。

以下範例使用 XmlTextWriter 來建立 XML 輸出。

Shared Sub WriteQuote(writer As XmlWriter, symbol As String, price As Double, change As Double, volume As Long)
   writer.WriteStartElement("Stock")
   writer.WriteAttributeString("Symbol", symbol)
   writer.WriteElementString("Price", XmlConvert.ToString(price))
   writer.WriteElementString("Change", XmlConvert.ToString(change))
   writer.WriteElementString("Volume", XmlConvert.ToString(volume))
   writer.WriteEndElement()
End Sub 'WriteQuote

Public Shared Sub Main()
   Dim writer As New XmlTextWriter(Console.Out)
   writer.Formatting = Formatting.Indented
   WriteQuote(writer, "MSFT", 74.125, 5.89, 69020000)
   writer.Close()
End Sub 'Main
static void WriteQuote(XmlWriter writer, string symbol, 
                double price, double change, long volume)
{
   writer.WriteStartElement("Stock");
   writer.WriteAttributeString("Symbol", symbol);
   writer.WriteElementString("Price", XmlConvert.ToString(price));
   writer.WriteElementString("Change", XmlConvert.ToString(change));
   writer.WriteElementString("Volume", XmlConvert.ToString(volume));
   writer.WriteEndElement();
}

public static void Main(){
    XmlTextWriter writer = new XmlTextWriter(Console.Out);
    writer.Formatting = Formatting.Indented;
    WriteQuote(writer, "MSFT", 74.125, 5.89, 69020000);
    writer.Close();
}

輸出

<Stock Symbol="MSFT">
      <Price>74.125</Price>
      <Change>5.89</Change>
      <Volume>69020000</Volume>
</Stock>

WriteQuote 方法的輸入是股票代號,它以 string 方式表示。股價與變動會宣告為 double,而交易量為 long。若要將這些變數轉換為字串,必須使用 XmlConvert 類別。它有將所有強式資料型別轉換為字串的方法。除此之外,XmlConvert 類別也有可將字串轉換成 Microsoft .NET Framework 資料型別的相反轉換方法。如需詳細資訊,請參閱 XML 名稱的字元編碼和 XML 資料型別轉換

如需示範將 XML 寫至檔案的程式碼範例,請參閱 XmlTextWriter.WriteProcessingInstruction。如需示範將 XML 寫至主控台的程式碼範例,請參閱 XmlTextWriter.WriteString

下列程式碼顯示如何寫入可產生 <price>19.95</price> 的項目:

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

下列程式碼顯示如何寫入可產生 <element name="purchaseOrder"/> 的屬性:

writer.WriteStartElement("element")
writer.WriteAttributeString("name", "purchaseOrder")
writer.WriteEndElement()
writer.WriteStartElement("element"); 
writer.WriteAttributeString("name", "purchaseOrder"); 
writer.WriteEndElement();

WriteAttributeString 方法寫入屬性和命名空間宣告

WriteAttributeString 方法有兩個不同的工作。一個工作用來寫出屬性,並將它們與使用者定義的命名空間前置詞產生關聯。第二個工作用來產生命名空間宣告。如果寫入的屬性和 LocalName 參數是 xmlns,則這個方法會被視為建立命名空間宣告。

在下列程式碼範例中,WriteAttributeString 方法可用來在項目內寫入屬性。

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

WriteAttributeString 也會依據它所找到的內容來逸出屬性的文字內容。如果使用雙引號,則 XmlTextWriter 會使用 &quot; 在屬性值的文字內容中將它們逸出。如果使用單引號,則會使用 &apos; 來逸出屬性值的文字內容。

若要產生命名空間宣告,有一個多載的 WriteAttributeString 方法可以允許應用程式定義命名空間宣告。下列程式碼範例建立兩個預設的命名空間。第一個宣告會將沒有前置詞的所有項目繫結至第一個命名空間宣告,而以 "po" 前置詞宣告的所有項目則會繫結至第二個命名空間宣告。

' Write the default namespace, identified as xmlns with no prefix
writer.WriteAttributeString("xmlns", Nothing, "http://www.w3.org/2000/10/XMLSchema")
' Write a namespace for the purchase order with a prefix of "po"
writer.WriteAttributeString("xmlns", "po", Nothing, "https://contoso.com/po")
// Write the default namespace, identified as xmlns with no prefix
writer.WriteAttributeString("xmlns", null, "http://www.w3.org/2000/10/XMLSchema");
// Write a namespace for the purchase order with a prefix of "po"
writer.WriteAttributeString("xmlns", "po", null, "https://contoso.com/po");

Close 方法

Close 方法會在關閉資料流時檢查 XML 文件是否有效。這可以防止建立無效的 XML 文件,並確保 XML 的格式正確。除關閉資料流之外,Close 方法也會呼叫所有必要的 WriteEnd<xxx> 方法來關閉文件。

方法配對

XmlWriter 中的方法也會以成對的方式出現;WriteStartDocumentWriteEndDocumentWriteStartElementWriteEndElementWriteStartAttributeWriteEndAttribute 等方法會兩兩配對。例如,使用這些方法,您可以建立巢狀項目或屬性。使用這些方法配對可以建置 XML 文件,且允許建立複雜的項目或屬性。

WriteStartDocument 和 WriteEndDocument 方法

WriteStartDocument 啟動一個新文件,並寫入版本屬性設定為 "1.0" 的 XML 宣告,WriteEndDocument 則關閉該文件。在呼叫下一個 WriteStartDocument 以開始寫入下一份文件之間,可修改格式、縮排和其他的屬性。WriteStartDocument 方法會以程式設計方式辨認正被寫入的 XML 文件,並套用根層次規則。如果未使用這個方法,則會建立 XML 片段,並確認它的格式是否正確。不套用根層次規則。下列程式碼範例顯示文件的開頭和結尾。

' Write the XML declaration.writer.WriteStartDocument()
...
'Close the document.writer.WriteEndDocument()
// Write the XML declaration.writer.WriteStartDocument();
...// Close the document.writer.WriteEndDocument();

WriteStartElement 和 WriteEndElement 方法

WriteStartElementWriteEndElement 方法配對會分隔一或多個項目。在所有被覆寫的 WriteStartElement 方法中,開始標記的區域名稱是必要的參數。下列程式碼使用 WriteStartElementWriteEndElement 方法配對。

' Write the title.writer.WriteStartElement("title")
writer.WriteString("The Handmaid's Tale")
writer.WriteEndElement()
// Write the title.writer.WriteStartElement("title");
writer.WriteString("The Handmaid's Tale");
writer.WriteEndElement();

輸出

<title>The Handmaid's Tale</title>

WriteStartElement 提供覆寫方法簽名碼 (Signature),使程式碼能夠對它的項目指定命名空間前置詞。如需詳細資訊,請參閱 XmlTextWriter 中的項目命名空間前置詞

WriteStartAttribute 和 WriteEndAttribute 方法

WriteStartAttributeWriteEndAttribute 與其他的開始和結束方法相似,除了這些方法開始和結束屬性以外。WriteStartAttribute 會寫入屬性的開頭,WriteString 方法可用來寫入屬性值,而 WriteEndAttribute 會結束屬性標記。下列程式碼範例顯示 WriteStartAttributeWriteEndAttribute 方法配對。

writer.WriteStartAttribute(prefix, "ISBN", "urn:samples")
writer.WriteString("1-861003-78")
writer.WriteEndAttribute()
writer.WriteStartAttribute(prefix, "ISBN", "urn:samples");
writer.WriteString("1-861003-78");
writer.WriteEndAttribute();

輸出

<book bk:ISBN="1-861003-78">

WriteStartAttribute 有一個會使應用程式能夠指定命名空間前置詞的多載方法,使得它能夠將命名空間前置詞與它寫入的屬性產生關聯。如需詳細資訊,請參閱 XmlTextWriter 中的屬性命名空間前置詞

請參閱

參考

XmlTextWriter

XmlTextWriter

XmlWriter

XmlWriter

概念

以 XmlTextWriter 格式化的 XML 輸出

XmlTextWriter 內的命名空間功能

其他資源

使用 XmlWriter 寫入 XML