views:

2668

answers:

2

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...

+6  A: 

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);
Daren Thomas
Works like a charm. You should mark this as the answer.
AJ
done. feel a bit funny accepting my own answer, though...
Daren Thomas
+1  A: 

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.

ManBugra