C# - Change the Encoding of an XmlDocument

By , 9/15/2008
(1 ratings)
Example:

before: <xml version="1.0" encoding="utf-16"?>
after: <xml version="1.0" encoding="utf-8"?>

needed namespace: System.Xml;
/// <summary>
/// Changes the XML encoding.
/// </summary>
/// <param name="xmlDoc">The XmlDocument.</param>
/// <param name="newEncoding">The new encoding.</param>
/// <returns></returns>
private XmlDocument ChangeXmlEncoding(XmlDocument xmlDoc, string newEncoding)
{
    if (xmlDoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
    {
        XmlDeclaration xmlDeclaration = (XmlDeclaration)xmlDoc.FirstChild;
        xmlDeclaration.Encoding = newEncoding;
    }
    return xmlDoc;
}

Tagged with xml, encoding.

Comments

 

Log in, to comment!