XmlDeclaration.Encoding Property


The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Gets or sets the encoding level of the XML document.

Namespace:   System.Xml
Assembly:  System.Xml (in System.Xml.dll)

public string Encoding { get; set; }

Property Value

Type: System.String

The valid character encoding name. The most commonly supported character encoding names for XML are the following:


Encoding Names


UTF-8, UTF-16

ISO 10646

ISO-10646-UCS-2, ISO-10646-UCS-4

ISO 8859

ISO-8859-n (where "n" is a digit from 1 to 9)

JIS X-0208-1997

ISO-2022-JP, Shift_JIS, EUC-JP

This value is optional. If a value is not set, this property returns String.Empty.

If an encoding attribute is not included, UTF-8 encoding is assumed when the document is written or saved out.

Unlike most XML attributes, encoding attribute values are not case-sensitive. This is because encoding character names follow ISO and Internet Assigned Numbers Authority (IANA) standards.

The following example creates an XmlDeclaration node and adds it to an XML document.

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);

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

    // Display the modified XML document 


Universal Windows Platform
Available since 10
.NET Framework
Available since 1.1
Return to top