i have the following code:
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()));
And here is the output:
<?xml version="1.0" encoding="utf-16"?>
<myRoot>myInnerText</myRoot>
???<?xml version="1.0" encoding="UTF-8"?>
<myRoot>myInnerText</myRoot>
Basically what it does is make an xml file, and set the encoding to utf8, but when it saves it to stringwriter it ignores my encoding and uses utf16. However, when using a memory stream, it uses utf8 (with the extra BOM chars)
Why is this? Why isn't it honouring my explicit encoding setting of utf-8?
Thanks a lot
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…