我有以下代码,我想用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));
最佳答案
XML输出将包含一个基于流编码的头,而不是设置中指定的编码。由于字符串是16位unicode,编码将是utf-16。解决方法是抑制头并自己添加:
writerSettings.OmitXmlDeclaration = true;
然后,当您从StringBuilder获得结果时:
string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + sb.ToString();