XslTransform doesn't write Xml Declaration with XmlDocument

Took quite some time to find out, but it seems as though the System.Xml.Xsl.XslTransform.Transform method does not write the Xml Declaration when you pass it a System.Xml.XmlDocument. Given the following Xml input (simple.xml):

<root>SomeData<root>

And this xsl stylesheet (simple.xslt):

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" />

According to this article the result should include the Xml Declaration by default.
I tested using this code:

System.Xml.Xsl.XslTransform xslt = new System.Xml.Xsl.XslTransform();
xslt.Load("c:\\simple.xslt");
XmlDocument xml = new
XmlDocument();
xml.Load("c:\\simple.xml");
System.IO.Stream stream = new
System.IO.MemoryStream();
XmlWriter xw = new
System.Xml.XmlTextWriter(stream, System.Text.Encoding.UTF8);
xslt.Transform(xml, null, xw);

The XmlWriter contains only "SomeData" when this code has executed. If I use a XPathDocument instead of the XmlDocument though:

System.Xml.Xsl.XslTransform xslt = new System.Xml.Xsl.XslTransform();
xslt.Load("c:\\simple.xslt");
System.Xml.XPath.XPathDocument xml = new
System.Xml.XPath.XPathDocument("c:\\simple.xml");
System.IO.Stream stream = new
System.IO.MemoryStream();
xslt.Transform(xml, null, stream);

Then the output is as following:

<xml version="1.0" encoding="utf-8"?>SomeData

Anybody know why?

Filed under:

Comments

# David Findley said:

Check out: http://www.w3schools.com/xsl/el_output.asp

I think all you need to do is put in an <xsl:output omit-xml-declaration="no" />
int your XSLT.

If thats not it then make sure you have the Xml declaration in your XSLT as well.

Friday, May 23, 2003 2:32 AM
# Mads said:

I am pretty sure I actually tried both of those approaches.

Friday, May 23, 2003 11:29 PM