When saving an XmlDocument, it ignores the encoding in the XmlDeclaration (UTF8) and uses UTF16

前端 未结 3 1479
無奈伤痛
無奈伤痛 2020-12-15 17:19

i have the following code:

var doc = new XmlDocument();

XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration(\"1.0\", \"UTF-8\", null);
doc.AppendChild(         


        
3条回答
  •  悲&欢浪女
    2020-12-15 18:03

    Because all you are doing is setting an XML element that says it's UTF-8, you aren't actually saving it as UTF-8. You need to set the output stream to use UTF-8, like this:

    var doc = new XmlDocument();
    XmlElement root = doc.CreateElement("myRoot");
    doc.AppendChild(root);
    root.InnerText = "myInnerText";
    using(TextWriter sw = new StreamWriter("C:\\output.txt", false, Encoding.UTF8)) //Set encoding
    {
        doc.Save(sw);
    }
    

    Once you do that, you don't even have to add the XML declaration. It figures it out on its own. If you want to save it to a MemoryStream, use a StreamWriter that wraps the MemoryStream.

提交回复
热议问题