XslCompiledTransform 使用 UTF-16 编码
我有以下代码,我想使用UTF-8编码格式输出xml数据。但它总是以 UTF-16 输出数据:
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(XmlReader.Create(new StringReader(xsltString), new XmlReaderSettings()));
StringBuilder sb = new StringBuilder();
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.Encoding = Encoding.UTF8;
writerSettings.Indent = true;
xslt.Transform(XmlReader.Create(new StringReader(inputXMLToTransform)), XmlWriter.Create(sb, writerSettings));
I have the following code, which I want to output xml data using the UTF-8 encoding format. but it always outputs data in UTF-16 :
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(XmlReader.Create(new StringReader(xsltString), new XmlReaderSettings()));
StringBuilder sb = new StringBuilder();
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.Encoding = Encoding.UTF8;
writerSettings.Indent = true;
xslt.Transform(XmlReader.Create(new StringReader(inputXMLToTransform)), XmlWriter.Create(sb, writerSettings));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
XML 输出将包含基于流编码的标头,而不是设置中指定的编码。由于字符串是 16 位 unicode,因此编码将为 UTF-16。解决方法是抑制标头并自己添加它:然后
,当您从 StringBuilder 获取结果时:
The XML output will contain a header that is based on the encoding of the stream, not the encoding specified in the settings. As strings are 16 bit unicode the encoding will be UTF-16. The workaround is to suppress the header and add it yourself instead:
Then when you get the result from the StringBuilder:
如果您使用
MemoryStream
代替StringBuilder
,则XmlWriter
将遵循您在XmlWriterSettings
中指定的编码,因为MemoryStream
没有像StringBuilder
那样的固有编码。If you use a
MemoryStream
in place of theStringBuilder
, theXmlWriter
will respect the encoding you specify in theXmlWriterSettings
, since theMemoryStream
doesn't have an inherent encoding like theStringBuilder
does.