How to apply an XSLT Stylesheet in C#


I want to apply an XSLT Stylesheet to an XML Document using C# and write the output to a File.

This question is tagged with c# xml xslt

~ Asked on 2008-08-29 07:10:31

4 Answers


I found 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 my trusty compiler says, XslTransform is obsolete: Use XslCompiledTransform instead:

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

~ Answered on 2008-08-29 07:10:36


Based on Daren's excellent answer, note that this code can be shortened significantly by using the appropriate XslCompiledTransform.Transform overload:

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

(Sorry for posing this as an answer, but the code block support in comments is rather limited.)

In VB.NET, you don't even need a variable:

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

~ Answered on 2012-05-15 07:40:46


Here is a tutorial about how to do XSL Transformations in C# on MSDN:

and here how to write files:

just as a side note: if you want to do validation too here is another tutorial (for DTD, XDR, and XSD (=Schema)):

i added this just to provide some more information.

~ Answered on 2010-10-26 10:55:03


This might help you

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 on 2019-11-19 09:34:10

Most Viewed Questions: