XmlDeclaration.Encoding 屬性

定義

取得或設定 XML 文件的編碼方式層級。

public:
 property System::String ^ Encoding { System::String ^ get(); void set(System::String ^ value); };
public string Encoding { get; set; }
member this.Encoding : string with get, set
Public Property Encoding As String

屬性值

String

有效的字元編碼名稱。 最常支援的 XML 字元編碼名稱如下:

類別 編碼名稱
Unicode UTF-8、UTF-16
ISO 10646 ISO-10646-UCS-2, ISO-10646-UCS-4
ISO 8859 ISO-8859-n (其中 "n" 可以是 1 到 9 的數字)
JIS X-0208-1997 ISO-2022-JP, Shift_JIS, EUC-JP

此為選用值。 如果沒有設定值,這個屬性會傳回 String.Empty。

如果未包含編碼方式屬性,在文件被寫入或儲存時會假設為 UTF-8 編碼方式。

範例

下列範例會 XmlDeclaration 建立節點,並將其新增至 XML 檔。

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   
   // Create and load the XML document.
   XmlDocument^ doc = gcnew XmlDocument;
   String^ xmlString = "<book><title>Oberon's Legacy</title></book>";
   doc->Load( gcnew StringReader( xmlString ) );
   
   // Create an XML declaration. 
   XmlDeclaration^ xmldecl;
   xmldecl = doc->CreateXmlDeclaration( "1.0", nullptr, nullptr );
   xmldecl->Encoding = "UTF-8";
   xmldecl->Standalone = "yes";
   
   // Add the new node to the document.
   XmlElement^ root = doc->DocumentElement;
   doc->InsertBefore( xmldecl, root );
   
   // Display the modified XML document 
   Console::WriteLine( doc->OuterXml );
}
using System;
using System.IO;
using System.Xml;

public class Sample {

  public static void Main() {

    // Create and load the XML document.
    XmlDocument doc = new XmlDocument();
    string xmlString = "<book><title>Oberon's Legacy</title></book>";
    doc.Load(new StringReader(xmlString));

    // Create an XML declaration.
    XmlDeclaration xmldecl;
    xmldecl = doc.CreateXmlDeclaration("1.0",null,null);
    xmldecl.Encoding="UTF-8";
    xmldecl.Standalone="yes";

    // Add the new node to the document.
    XmlElement root = doc.DocumentElement;
    doc.InsertBefore(xmldecl, root);

    // Display the modified XML document
    Console.WriteLine(doc.OuterXml);
  }
}
Imports System.IO
Imports System.Xml

public class Sample 

  public shared sub Main() 
   
    ' Create and load the XML document.
    Dim doc as XmlDocument = new XmlDocument()
    Dim xmlString as string = "<book><title>Oberon's Legacy</title></book>"
    doc.Load(new StringReader(xmlString))
  
    ' Create an XML declaration. 
    Dim xmldecl as XmlDeclaration 
    xmldecl = doc.CreateXmlDeclaration("1.0",nothing, nothing)
    xmldecl.Encoding="UTF-8"
    xmldecl.Standalone="yes"     
      
    ' Add the new node to the document.
    Dim root as XmlElement = doc.DocumentElement
    doc.InsertBefore(xmldecl, root)
    
    ' Display the modified XML document 
    Console.WriteLine(doc.OuterXml)
      
  end sub
end class

備註

不同于大部分的 XML 屬性,編碼屬性值不會區分大小寫。 這是因為編碼字元名稱遵循 ISO 和網際網路指派號碼授權單位 (IANA) 標準。

適用於