XslCompiledTransform使用UTF-16编码XslCompiledTransform、UTF

由网友(稚气)分享简介:我有以下的code,我想使用UTF-8编码格式输出XML数据。但它总是以UTF-16输出数据:I have the following code, which I want to output xml data using the UTF-8 encoding format. but it always output...

我有以下的code,我想使用UTF-8编码格式输出XML数据。但它总是以UTF-16输出数据:

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

推荐答案

XML输出​​将包含一个,基于该流,而不是在设置中指定的编码的编码标题。由于字符串是16位单code编码将是UTF-16。解决方法是晚饭preSS页眉和自己添加它来代替:

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;

然后,当你从StringBuilder的得到的结果:

Then when you get the result from the StringBuilder:

string xml = "<?xml version="1.0" encoding="UTF-8"?>rn" + sb.ToString();
阅读全文

相关推荐

最新文章