Exclude XML directive from XslCompiledTransform.Transform output

I use XsltCompiledTransform to convert some XML to an HTML fragment (not a complete HTML document, but only a DIV, which I will include in a page generated elsewhere).

I am doing the following conversion:

 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 conversion result always starts with this XML directive:

 <?xml version="1.0" encoding="utf-16"?> 

How can I prevent this from appearing in my converted data?

EDIT:

I'm telling XSLT that I don't want it to display an xml declaration using

 <xsl:output method="html" version="4.0" omit-xml-declaration="yes"/> 

but this does not seem to affect the directive that appeared on my output.

Interestingly, both my XML data source and my XSLT transform define themselves as UTF-8 not UTF-16 .

UPDATE: It seems that UTF-16 appears because I use a string (builder) as the output mechanism. When I change the code to use a MemoryStream instead of a StringBuilder , my UTF-8 encoding is saved. I guess this has something to do with the inner workings of the string type and how it relates to coding.

+6
c # xml xslt xslcompiledtransform
source share
2 answers

You need to use the XmlWriterSettings object. Set its properties to omit the XML declaration and pass it to the constructor of your XmlWriter .

 StringBuilder output = new StringBuilder(); XmlReader rawData = BusinessObject.GetXml(); XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.OmitXmlDeclaration = true; using (XmlWriter transformedData = XmlWriter.Create(output, writerSettings)) { XslCompiledTransform transform = new XslCompiledTransform(); transform.Load("stylesheet.xslt"); transform.Transform(data, transformedData); Response.Write(output.ToString()); } 
+14
source share

The easiest way is to add this node to your XSLT:

 <xsl:output method="html" omit-xml-declaration="yes"/> 
+3
source share

All Articles