相关疑难解决方法(0)

保存XmlDocument时,它忽略XmlDeclaration(UTF8)中的编码并使用UTF16

我有以下代码:

var doc = new XmlDocument();

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

XmlElement root = doc.CreateElement("myRoot");
doc.AppendChild(root);
root.InnerText = "myInnerText";

StringWriter sw = new StringWriter();
doc.Save(sw);
Console.WriteLine(sw.ToString());

Console.WriteLine();

MemoryStream ms = new MemoryStream();
doc.Save(ms);
Console.WriteLine(Encoding.ASCII.GetString(ms.ToArray()));
Run Code Online (Sandbox Code Playgroud)

这是输出:

<?xml version="1.0" encoding="utf-16"?>
<myRoot>myInnerText</myRoot>

???<?xml version="1.0" encoding="UTF-8"?>
<myRoot>myInnerText</myRoot>
Run Code Online (Sandbox Code Playgroud)

基本上它的作用是创建一个xml文件,并将编码设置为utf8,但是当它将它保存到字符串编写器时,它会忽略我的编码并使用utf16.但是,在使用内存流时,它使用utf8(带有额外的BOM表字符)

为什么是这样?为什么不尊重我对utf-8的显式编码设置?

非常感谢

c# xml

23
推荐指数
2
解决办法
4万
查看次数

标签 统计

c# ×1

xml ×1