Cómo aplicar una hoja de estilos XSLT en C#
Pregunta
Quiero aplicar una hoja de estilos XSLT para un Documento XML utilizando C# y escribir en la salida a un Archivo.
Solución
He encontrado una posible respuesta aquí: http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63
Desde el artículo:
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;
Editar:
Pero mi fiel compilador dice, XslTransform
es obsoleto:Uso XslCompiledTransform
lugar:
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);
myXslTrans.Transform(myXPathDoc,null,myWriter);
Otros consejos
Basado en Daren excelente respuesta, tenga en cuenta que este código puede reducirse significativamente mediante el adecuado XslCompiledTransform.Transformar la sobrecarga de:
var myXslTrans = new XslCompiledTransform();
myXslTrans.Load("stylesheet.xsl");
myXslTrans.Transform("source.xml", "result.html");
(Lo siento para plantear esto como una respuesta, pero la code block
apoyo en los comentarios es bastante limitado.)
En VB.NET usted no necesita una variable:
With New XslCompiledTransform()
.Load("stylesheet.xsl")
.Transform("source.xml", "result.html")
End With
Aquí hay un tutorial acerca de cómo hacer las Transformaciones XSL en C# en MSDN:
http://support.microsoft.com/kb/307322/en-us/
y aquí cómo escribir archivos:
http://support.microsoft.com/kb/816149/en-us
sólo como nota lateral:si usted desea hacer la validación también aquí otro tutorial (para DTD, XSD, y XSD (=Schema)):
http://support.microsoft.com/kb/307379/en-us/
he añadido esto sólo para proporcionar algo más de información.