我想使用C#将XSLT样式表应用于XML文档,并将输出写入文件。
我在这里找到了可能的答案:http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63
从文章:
1 2 3 4 5
| 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代替:
1 2 3 4 5
| 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重载可以大大缩短此代码:
1 2 3
| var myXslTrans = new XslCompiledTransform();
myXslTrans.Load("stylesheet.xsl");
myXslTrans.Transform("source.xml","result.html"); |
(很抱歉将其作为答案,但是注释中的code block支持非常有限。)
在VB.NET中,您甚至不需要变量:
1 2 3 4
| 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/
我添加此只是为了提供更多信息。
这可能对您有帮助
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public static string TransformDocument(string doc, string stylesheetPath)
{
Func<string,XmlDocument> GetXmlDocument = (xmlContent) =>
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlContent);
return xmlDocument;
};
try
{
var document = GetXmlDocument(doc);
var style = GetXmlDocument(File.ReadAllText(stylesheetPath));
System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();
transform.Load(style); // compiled stylesheet
System.IO.StringWriter writer = new System.IO.StringWriter();
XmlReader xmlReadB = new XmlTextReader(new StringReader(document.DocumentElement.OuterXml));
transform.Transform(xmlReadB, null, writer);
return writer.ToString();
}
catch (Exception ex)
{
throw ex;
}
} |