I'm trying to do xsl transform in .net that outputs another xsl stylesheet. I'm outputting to text to see as I'm building. However, I'm getting the following error:
Server Error in '/' Application.
Token Text in state Start would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Token Text in state Start would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment.
Source Error:
Line 33: xslt.Load(xrt);
Line 34:
Line 35: xslt.Transform(xri, xal, xwo);
Line 36: }
Line 37: out11.InnerHtml = sw.ToString();
Here's entire code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Xsl;
namespace WebApplication1
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//http://stackoverflow.com/q/2384306/139698
string transform = GetXsl();
string input = GetXml();
StringWriter sw = new StringWriter();
using (XmlReader xrt = XmlReader.Create(new StringReader(transform)))
using (XmlReader xri = XmlReader.Create(new StringReader(input)))
using (XmlWriter xwo = XmlWriter.Create(sw))
{
XsltArgumentList xal = new XsltArgumentList();
xal.AddExtensionObject(
MyXsltExtensionFunctions.Namespace,
new MyXsltExtensionFunctions());
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(xrt);
xslt.Transform(xri, xal, xwo);
}
out11.InnerHtml = sw.ToString();
}
private string GetXml()
{
return
@"<?xml version='1.0' encoding='UTF-8'?>
<catalog>
<data id='1' option1='key1' option2='0' />
<data id='2' option1='' option2='1' />
</catalog>
";
}
private string GetXsl()
{
return
@"<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
xmlns:msxsl='urn:schemas-microsoft-com:xslt' exclude-result-prefixes='msxsl'
xmlns:ext='http://XsltSampleSite.XsltFunctions/1.0'
xmlns:xslout='blah'>
<xsl:output method='text'/>
<xslout:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:template match='/'>
<span>
<xsl:value-of select=""ext:HelloWorld()"" />
</span>
</xsl:template>
</xslout:stylesheet>
</xsl:stylesheet>
";
}
}
public class MyXsltExtensionFunctions
{
public const string Namespace = "http://XsltSampleSite.XsltFunctions/1.0";
public string HelloWorld()
{
return "It works!";
}
}
}