Friday, February 4, 2011

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.

Edit:

@Rob Cooper: Yes, I am aware of that. But I couldn't find it in SO. The Idea of this site is to collect answers to any question a developer could have, right? I had this question today and thus posted an answer. Next time I look (this is not the first time I forgot the actual classes to use) I will know where to find the answer - StackOverflow.

Is this clogging up? I don't really think so...

  • I found a possible answer here: http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63

    From the article:

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

    Edit:

    But my trusty compiler says, XslTransform is obsolete: Use XslCompiledTransform instead:

    XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
    XslCompiledTransform myXslTrans = new XslCompiledTransform();
    myXslTrans.Load(myStyleSheet);
    XmlTextWriter myWriter = new XmlTextWriter("result.html",null);
    myXslTrans.Transform(myXPathDoc,null,myWriter);
    
    AJ : Works like a charm. You should mark this as the answer.
    Daren Thomas : done. feel a bit funny accepting my own answer, though...
  • Here is a tutorial about how to do XSL Transformations in C# on MSDN:

    http://support.microsoft.com/kb/307322/en-us/

    and here how to write files:

    http://support.microsoft.com/kb/816149/en-us

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

    http://support.microsoft.com/kb/307379/en-us/

    i added this just to provide some more information.

    From ManBugra

0 comments:

Post a Comment