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

前端 未结 3 1481
無奈伤痛
無奈伤痛 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 17:58

    I use the following method, it writes it out pretty and as UTF-8

    public static string Beautify(XmlDocument doc)
    {
        string xmlString = null;
        using (MemoryStream ms = new MemoryStream()) {
            XmlWriterSettings settings = new XmlWriterSettings {
                Encoding = new UTF8Encoding(false),
                Indent = true,
                IndentChars = "  ",
                NewLineChars = "\r\n",
                NewLineHandling = NewLineHandling.Replace
            };
            using (XmlWriter writer = XmlWriter.Create(ms, settings)) {
                doc.Save(writer);
            }
            xmlString = Encoding.UTF8.GetString(ms.ToArray());
        }
        return xmlString;
    }
    

    Call it like:

    File.WriteAllText(fileName, Utilities.Beautify(xmlDocument));
    

提交回复
热议问题