题
我想使用 C# 将 XSLT 样式表应用到 XML 文档,并将输出写入文件。
解决方案
我在这里找到了一个可能的答案: http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63
来自文章:
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;
编辑:
但我值得信赖的编译器说, XslTransform
已过时:使用 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);
其他提示
根据达伦的出色回答,请注意,通过使用适当的方法可以显着缩短此代码 XslCompiledTransform.Transform 重载:
var myXslTrans = new XslCompiledTransform();
myXslTrans.Load("stylesheet.xsl");
myXslTrans.Transform("source.xml", "result.html");
(很抱歉将此作为答案,但是 code block
评论中的支持相当有限。)
在 VB.NET 中,您甚至不需要变量:
With New XslCompiledTransform()
.Load("stylesheet.xsl")
.Transform("source.xml", "result.html")
End With
以下是 MSDN 上有关如何用 C# 进行 XSL 转换的教程:
http://support.microsoft.com/kb/307322/en-us/
这里是如何写入文件:
http://support.microsoft.com/kb/816149/en-us
正如旁注:如果您也想进行验证,这里有另一个教程(针对 DTD、XDR 和 XSD (=Schema)):
http://support.microsoft.com/kb/307379/en-us/
我添加这个只是为了提供更多信息。
不隶属于 StackOverflow