Search code examples
xmlserializationxsltpretty-print

How to format/indent output of an XSL Transformation


I am trying to output a fragment of html code. But I need it to be pretty-printed/indented. Is there any way to do this without using <xsl:text>&#xa;</xsl:text> and <xsl:text>&#9;</xsl:text>?

I have used the following line without any results.

<xsl:output method="html" indent="yes"/>

Follwoing is the c# code;

    XslCompiledTransform XSLT = new XslCompiledTransform();
    XSLT.Load(xslPath);

    using (XmlTextWriter writer = new XmlTextWriter(writePath, null))
    {
        if (isTopLevel)
        {
            XSLT.Transform(XMLDocumentForCurrentUser, writer);
        }
        else
        {
            XsltArgumentList xslArg = new XsltArgumentList();
            xslArg.AddParam("MenuIndex", "", menuIndex);
            XSLT.Transform(XMLDocumentForCurrentUser, xslArg, writer);
        }
    }
 // I write the output to file  
//All this works fine, only now I need the HTML to be readable (in the browser's view source or any notepad)

Does anybody know of a way to format(atleast indent) XSLT output?


Solution

  • Don't create your own XmlTextWriter if you want the XSLT processor to apply the xsl:output directive. Instead either write directly to a file or create an XmlWriter as follows:

    using (XmlWriter result = XmlWriter.Create(writePath, XSLT.OutputSettings))
    {
            if (isTopLevel)
            {
                XSLT.Transform(XMLDocumentForCurrentUser, result);
            }
            else
            {
                XsltArgumentList xslArg = new XsltArgumentList();
                xslArg.AddParam("MenuIndex", "", menuIndex);
                XSLT.Transform(XMLDocumentForCurrentUser, xslArg, result);
            }
    }