我有以下代码,我想使用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));
答案 0 :(得分:13)
XML输出将包含基于流编码的标头,而不是设置中指定的编码。由于字符串是16位unicode,编码将是UTF-16。解决方法是禁止标题并自行添加:
writerSettings.OmitXmlDeclaration = true;
然后当你从StringBuilder获得结果时:
string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + sb.ToString();
答案 1 :(得分:7)
如果您使用MemoryStream
代替StringBuilder
,XmlWriter
将尊重您在XmlWriterSettings
中指定的编码,因为MemoryStream
不会没有像StringBuilder
那样的固有编码。