Voglio applicare un foglio di stile XSLT a un documento XML utilizzando C # e scrivere l’output su un file.
Ho trovato una ansible risposta qui: http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63
Dall’articolo:
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ; XslTransform myXslTrans = new XslTransform() ; myXslTrans.Load(myStyleSheet); XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ; myXslTrans.Transform(myXPathDoc,null,myWriter) ;
Modificare:
Ma il mio fidato compilatore dice che XslTransform
è obsoleto: usa invece XslCompiledTransform
:
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ; XslCompiledTransform myXslTrans = new XslCompiledTransform(); myXslTrans.Load(myStyleSheet); XmlTextWriter myWriter = new XmlTextWriter("result.html",null); myXslTrans.Transform(myXPathDoc,null,myWriter);
Sulla base dell’eccellente risposta di Daren, si noti che questo codice può essere abbreviato in modo significativo utilizzando l’appropriato XslCompiledTransform.Transform overload :
var myXslTrans = new XslCompiledTransform(); myXslTrans.Load("stylesheet.xsl"); myXslTrans.Transform("source.xml", "result.html");
(Ci scusiamo per aver proposto questa risposta come risposta, ma il supporto del code block
nei commenti è piuttosto limitato).
In VB.NET, non hai nemmeno bisogno di una variabile:
With New XslCompiledTransform() .Load("stylesheet.xsl") .Transform("source.xml", "result.html") End With
Ecco un tutorial su come eseguire le trasformazioni XSL in C # su MSDN:
http://support.microsoft.com/kb/307322/en-us/
e qui come scrivere file:
http://support.microsoft.com/kb/816149/en-us
come nota a margine: se vuoi fare anche la validazione ecco un altro tutorial (per DTD, XDR e XSD (= Schema)):
http://support.microsoft.com/kb/307379/en-us/
l’ho aggiunto solo per fornire ulteriori informazioni.