从 XslCompiledTransform.Transform 输出中排除 XML 指令
我正在使用 XsltCompiledTransform
将一些 XML 转换为 HTML 片段(不是完整的 HTML 文档,只是我将包含在其他地方生成的页面中的 DIV)。
我正在按如下方式进行转换:
StringBuilder output = new StringBuilder();
XmlReader rawData = BusinessObject.GetXml();
XmlWriter transformedData = XmlWriter.Create(output);
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load("stylesheet.xslt");
transform.Transform(rawData, transformedData);
Response.Write(output.ToString());
我的问题是转换的结果始终以此 XML 指令开头:
<?xml version="1.0" encoding="utf-16"?>
如何防止它出现在转换后的数据中?
编辑:
我告诉 XSLT 我不希望它输出 xml 声明,
<xsl:output method="html" version="4.0" omit-xml-declaration="yes"/>
但这似乎对出现在我的输出中的指令没有影响。
有趣的是,我的 XML 数据源和 XSLT 转换都将自己指定为 UTF-8
而不是 UTF-16
。
更新: UTF-16 似乎出现是因为我使用字符串(生成器)作为输出机制。当我更改代码以使用 MemoryStream
而不是 StringBuilder
时,我的 UTF-8 编码将被保留。我猜这与 string
类型的内部工作原理及其处理编码的方式有关。
I'm using an XsltCompiledTransform
to transform some XML into a fragment of HTML (not a complete HTML document, just a DIV that I will include in page generated elsewhere).
I'm doing the transformation as follows:
StringBuilder output = new StringBuilder();
XmlReader rawData = BusinessObject.GetXml();
XmlWriter transformedData = XmlWriter.Create(output);
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load("stylesheet.xslt");
transform.Transform(rawData, transformedData);
Response.Write(output.ToString());
My problem is that the result of the transform always begins with this XML directive:
<?xml version="1.0" encoding="utf-16"?>
How do I prevent this from appearing in my transformed data?
EDIT:
I'm telling the XSLT that I don't want it to output an xml declaration with
<xsl:output method="html" version="4.0" omit-xml-declaration="yes"/>
but this seems to have no effect on the directive appearing in my output.
Interestingly, both my XML data source and my XSLT transform specify themselves as UTF-8
not UTF-16
.
UPDATE:
The UTF-16 seems to be appearing because I'm using a string(builder) as an output mechanism. When I change the code to use a MemoryStream
instead of a StringBuilder
, my UTF-8 encoding is preserved. I'm guessing this has something to do with the internal workings of the string
type and how it deals with encoding.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用
XmlWriterSettings
对象。设置其属性以省略 XML 声明,并将其传递给XmlWriter
的构造函数。You need to use an
XmlWriterSettings
object. Set its properties to omit the XML declaration, and pass it to the constructor of yourXmlWriter
.最简单的方法是将此节点添加到您的 XSLT 中:
The easiest way would be to add this node to your XSLT: