当保存一个XmlDocument,它忽略了编码的XmlDeclaration(UTF8),并使用UTF16 [英] When saving an XmlDocument, it ignores the encoding in the XmlDeclaration (UTF8) and uses UTF16

查看:568
本文介绍了当保存一个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()));

和这里是输出:

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

???<?xml version="1.0" encoding="UTF-8"?>
<myRoot>myInnerText</myRoot>



基本上它是使一个XML文件,并设置编码为utf8,但当它保存它的StringWriter它忽略了我的编码,并使用UTF16。然而,在使用内存流时,它使用UTF8(带额外的BOM字符)

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)

这是为什么?为什么是不是尊重UTF-8我明确的编码设置?

Why is this? Why isn't it honouring my explicit encoding setting of utf-8?

非常感谢

推荐答案

由于你正在做的是设置了说,这是UTF-8的XML元素,你实际上并没有将其保存为UTF-8。您需要设置输出流使用UTF-8,是这样的:

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);
}



一旦你这样做,你甚至不用添加XML声明。它的数字它自身。如果你想将其保存到一个MemoryStream,使用该包装将MemoryStream使用StreamWriter。

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.

这篇关于当保存一个XmlDocument,它忽略了编码的XmlDeclaration(UTF8),并使用UTF16的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆