XslCompiledTransform 使用 UTF-16 编码

发布于 2024-10-21 15:05:52 字数 585 浏览 2 评论 0原文

我有以下代码,我想使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

挥剑断情 2024-10-28 15:05:52

XML 输出将包含基于流编码的标头,而不是设置中指定的编码。由于字符串是 16 位 unicode,因此编码将为 UTF-16。解决方法是抑制标头并自己添加它:然后

writerSettings.OmitXmlDeclaration = true;

,当您从 StringBuilder 获取结果时:

string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + sb.ToString();

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:

writerSettings.OmitXmlDeclaration = true;

Then when you get the result from the StringBuilder:

string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + sb.ToString();
走走停停 2024-10-28 15:05:52

如果您使用 MemoryStream 代替 StringBuilder,则 XmlWriter 将遵循您在 XmlWriterSettings 中指定的编码,因为 MemoryStream 没有像 StringBuilder 那样的固有编码。

If you use a MemoryStream in place of the StringBuilder, the XmlWriter will respect the encoding you specify in the XmlWriterSettings, since the MemoryStream doesn't have an inherent encoding like the StringBuilder does.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文