I keep getting the above error when trying to transform XML that’s generated in code to a plain text output.
My .xsl file is:
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:text>Test</xsl:text>
</xsl:template>
</xsl:transform>
And my C# method code is:
if( !File.Exists( xslPath ) )
throw new Exception( "XSL File (" + xslPath + ") does not exist" );
XslTransform docXsl = new XslTransform();
docXsl.Load( xslPath );
XmlDocument docXml = new XmlDocument();
XmlElement emailNode = docXml.CreateElement("Email");
docXml.AppendChild( emailNode );
XmlResolver xres = null;
XmlReader xr = docXsl.Transform( docXml, null, xres );
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load( xr );
return xmldoc.OuterXml;
The XML generated is very simple, just
<Email/>
If I remove the node from the XSL, then I do not get the error.
I cannot find out why this is happening. Any help would be greatly appreciated.
Thanks
What is it that you want to achieve? If you use .NET 2.0 or later you shouldn’t use XslTransform at all, rather XslCompiledTransform. And if you want plain text output then it does not make any sense to try to load that transformation result into an XmlDocument as that object model is meant to contain a well-formed XML document and not some plain text. So that is the reason I think you get the error, your transformation result is plain text with a single text node and then you try to load that single text node into an XmlDocument which looks for a root element which does not exist.
Consider to tell is which .NET version you use/target and what kind of output you want (e.g. plain text file or string with the transformation result), then we can point you to the right overload of the Transform method of XslCompiledTransform http://msdn.microsoft.com/en-us/library/system.xml.xsl.xslcompiledtransform.transform.aspx to get that result.
For instance if your transformation input is an XmlDocument or other object implementing
IXPathNavigableyou can use http://msdn.microsoft.com/en-us/library/ms163435.aspx to transform to a StringWriter to get an String result as follows: