Coder Perfect

In C#, how do you apply an XSLT Stylesheet?


I’d like to use C# to apply an XSLT Stylesheet to an XML Document and save the result to a file.

Asked by Daren Thomas

Solution #1 I discovered a possible answer here:

From the article:

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;


But, according to my trusted compiler, XslTransform is no longer in use: Instead, use XslCompiledTransform:

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslCompiledTransform myXslTrans = new XslCompiledTransform();
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);

Answered by Daren Thomas

Solution #2

Note that, based on Daren’s good response, this code may be significantly shorter by using the necessary XslCompiledTransform. Overloading on transformations:

var myXslTrans = new XslCompiledTransform(); 
myXslTrans.Transform("source.xml", "result.html"); 

(I apologize for posting this as an answer, but comment code block support is pretty restricted.)

You don’t even need a variable in VB.NET:

With New XslCompiledTransform()
    .Transform("source.xml", "result.html")
End With

Answered by Heinzi

Solution #3

On MSDN, there’s a tutorial on how to do XSL Transformations in C#:

Here’s how to make a file:

As an aside, here’s another tutorial (for DTD, XDR, and XSD (=Schema)) if you want to conduct validation as well:

I included this simply to offer some context.

Answered by ManBugra

Solution #4

This could be beneficial.

public static string TransformDocument(string doc, string stylesheetPath)
    Func<string,XmlDocument> GetXmlDocument = (xmlContent) =>
         XmlDocument xmlDocument = new XmlDocument();
         return xmlDocument;

        var document = GetXmlDocument(doc);
        var style = GetXmlDocument(File.ReadAllText(stylesheetPath));

        System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();
        transform.Load(style); // compiled stylesheet
        System.IO.StringWriter writer = new System.IO.StringWriter();
        XmlReader xmlReadB = new XmlTextReader(new StringReader(document.DocumentElement.OuterXml));
        transform.Transform(xmlReadB, null, writer);
        return writer.ToString();
    catch (Exception ex)
        throw ex;


Answered by Vinod Srivastav

Post is based on