为什么我不能将 XDocument XDeclaration 编码类型设置为 iso-8859-1?
为什么下面的代码没有设置XML声明编码类型?它始终将编码设置为 utf-16。我错过了一些非常明显的东西吗?
var xdoc = new XDocument(
new XDeclaration("1.0", "iso-8859-1", null),
new XElement("root", "")
);
输出:
<?xml version="1.0" encoding="utf-16"?>
<root></root>
Why doesn't the following code set the XML declaration encoding type? It always sets the encoding to utf-16 instead. Am I missing something very obvious?
var xdoc = new XDocument(
new XDeclaration("1.0", "iso-8859-1", null),
new XElement("root", "")
);
output:
<?xml version="1.0" encoding="utf-16"?>
<root></root>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请参阅有关指定
TextWriter
编码的答案。顺便说一句:
ISO-8859-1
是字符集,而不是编码。Unicode
也是一种字符集,但UTF-16
是将Unicode
字符集编码为字节序列。您无法将文档的编码指定为ISO-8859-1
,就像您无法将文档的字符集指定为UTF-16
一样。请注意,Unicode
是本机字符集,UTF-16
是 .NET 和 JavaString< 的本机
Unicode
编码。 /code> 类和基于文本或基于字符串的操作。See the answer about specifying the
TextWriter
's encoding.As an aside:
ISO-8859-1
is a character-set, not an encoding.Unicode
is also a character-set, butUTF-16
is an encoding of theUnicode
character set into a sequence of bytes. You cannot specify a document's encoding asISO-8859-1
, just as you cannot specify a document's character-set asUTF-16
. Note thatUnicode
is the native character-set andUTF-16
is the nativeUnicode
encoding for both .NET and JavaString
classes and text-based or string-based operations.如前所述,.NET XML/Stream 写入实现从声明的 XML 编码以外的位置“拾取”或解释编码。我已经成功测试了一个可行的解决方案,如之前 Stackoverflow 帖子 中包含的 URL 中所述,
我希望这对某人有所帮助。
干杯
As stated, the .NET XML/Stream writing implementation 'picks up' or interprets the encoding from somewhere other than the declared XML encoding. I have successfully tested a working solution, as described at the URL contained within the earlier Stackoverflow post
I hope this helps somebody.
Cheers
我不知何故在这里找不到任何有效的答案,所以这里是一个实际的解决方案,它将在标头中输出所需的编码:
您获得 UTF-16 的原因是字符串在内存中使用 UTF-16 进行编码,并且作为只要您没有为 XML 的输出指定编码,它就会覆盖 XML 标头中的编码以匹配实际使用的编码。使用
XmlTextWriter
是指定不同编码的一种方法。如果您需要在内存中执行整个操作,您还可以让
XmlTextWriter
写入MemoryStream
,然后将其转换回string
。I somehow can't find any working answer here, so here is an actual solution which will output the wanted encoding in the header:
The reason why you are getting UTF-16 is that strings are encoded with UTF-16 in memory, and as long as you don't specify an encoding for the output of the XML, it will override the encoding in the XML header to match the actual encoding being used. Using an
XmlTextWriter
is one method of specifying a different encoding.You can also let the
XmlTextWriter
write to aMemoryStream
and then transform it back tostring
if you need to perform the whole operation in memory.