XmlDocument.CreateXmlDeclaration(String, String, String) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
建立 XmlDeclaration 一個節點,並設定指定的值。
public:
virtual System::Xml::XmlDeclaration ^ CreateXmlDeclaration(System::String ^ version, System::String ^ encoding, System::String ^ standalone);
public virtual System.Xml.XmlDeclaration CreateXmlDeclaration(string version, string encoding, string standalone);
abstract member CreateXmlDeclaration : string * string * string -> System.Xml.XmlDeclaration
override this.CreateXmlDeclaration : string * string * string -> System.Xml.XmlDeclaration
Public Overridable Function CreateXmlDeclaration (version As String, encoding As String, standalone As String) As XmlDeclaration
參數
- version
- String
該版本必須是「1.0」。
- encoding
- String
編碼屬性的值。 這是你儲存 XmlDocument 為檔案或串流時使用的編碼;因此必須設定為類別支援 Encoding 的字串,否則 Save(String) 會失敗。 若此編碼為 null String.Empty,則 Save 該方法不會在 XML 宣告上寫入編碼屬性,因此會使用預設的編碼 UTF-8。
注意:若將 XmlDocument 儲存為 a TextWriter 或 XmlTextWriter,則該編碼值將被捨棄。 取而代之的是,使用 或 TextWriter 的 XmlTextWriter 編碼方式。 這確保寫出的 XML 能以正確的編碼被讀取回傳。
- standalone
- String
該數值必須是「是」或「否」。 若此為 null 或 String.Empty,則 Save 該方法不會在 XML 宣告上寫入獨立屬性。
傳回
新 XmlDeclaration 節點。
例外狀況
或 standalone 的version值與上述定義不同。
範例
以下範例建立一個 XML 聲明並將其加入文件中。
using System;
using System.IO;
using System.Xml;
public class Sample
{
public static void Main()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +
"<title>Pride And Prejudice</title>" +
"</book>");
//Create an XML declaration.
XmlDeclaration xmldecl;
xmldecl = doc.CreateXmlDeclaration("1.0",null,null);
//Add the new node to the document.
XmlElement root = doc.DocumentElement;
doc.InsertBefore(xmldecl, root);
Console.WriteLine("Display the modified XML...");
doc.Save(Console.Out);
}
}
Option Explicit
Option Strict
Imports System.IO
Imports System.Xml
Public Class Sample
Public Shared Sub Main()
Dim doc As New XmlDocument()
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" & _
"<title>Pride And Prejudice</title>" & _
"</book>")
'Create an XML declaration.
Dim xmldecl As XmlDeclaration
xmldecl = doc.CreateXmlDeclaration("1.0", Nothing, Nothing)
'Add the new node to the document.
Dim root As XmlElement = doc.DocumentElement
doc.InsertBefore(xmldecl, root)
Console.WriteLine("Display the modified XML...")
doc.Save(Console.Out)
End Sub
End Class
備註
屬性是以節點上的 XmlDeclaration 特殊屬性形式暴露,而非節點 XmlAttribute 本身。
雖然此方法會在文件上下文中建立新物件,但不會自動將新物件加入文件樹。 要新增物件,必須明確呼叫其中一個節點插入方法。
根據 W3C 可擴充標記語言(XML)1.0 建議,節點 XmlDeclaration 必須是文件中的第一個節點。
此方法是 Microsoft 對文件物件模型(DOM)的擴充。