xslt用来将xml转换成不同格式,例如xml,html或者wml,下面文章我们介绍如何使用c# xslt将xml转换成html格式。
首先需要引用下面列出的命名空间:
System.Xml System.Xml.XPath System.Xml.Xsl
xml转换步骤如下:
1) 载入xml
XPathDocument myXPathDoc = new XPathDocument(<xml file path>) ;
2) 载入xslt文件:
XslTransform myXslTrans = new XslTransform() ;myXslTrans.Load(<xsl file path>);
3) 创建输出流,以备输出:
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
4) 做转换
myXslTrans.Transform(myXPathDoc,null,myWriter) ;
c#使用xslt转xml示例代码如下:
下面程序是命令行程序,该程序接收两个参数,第一个参数是xml文件的路径,第二个文件是xslt文件的路径。程序使用xslt将xml转成html保存在程序的目录中。
using System ;using System.IO ;using System.Xml ;using System.Xml.Xsl ;using System.Xml.XPath ;public class XmlTransformUtil{
public static void Main(string[] args){
if (args.Length == 2){
Transform(args[0], args[1]) ;
}else{
PrintUsage() ;
}
}
public static void Transform(string sXmlPath, string sXslPath){
try{
//load the Xml doc
XPathDocument myXPathDoc = new XPathDocument(sXmlPath) ;
XslTransform myXslTrans = new XslTransform() ;
//load the Xsl
myXslTrans.Load(sXslPath) ;
//create the output stream
XmlTextWriter myWriter = new XmlTextWriter
("result.html", null);
//do the actual transform of Xml
myXslTrans.Transform(myXPathDoc,null, myWriter);
myWriter.Close() ;
}catch(Exception e){
Console.WriteLine("Exception: {0}", e.ToString());
}
}
public static void PrintUsage(){
Console.WriteLine
("Usage: XmlTransformUtil.exe <xml path> <xsl path>");
}}
用到的xml程序如下:
sampledoc.xml
<company>
<name>XYZ Inc.</name>
<address1>One Abc Way</address1>
<address2>Some avenue</address2>
<city>Tech city</city>
<country>Neverland</country></company>
sample.xsl
<!--
- XSLT is a template based language to transform Xml documents
It uses XPath to select specific nodes
for processing.
- A XSLT file is a well formed Xml document
--><!-- every StyleSheet starts with this tag --><xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0"><!-- indicates what our output type is going to be --><xsl:output method="html" />
<!--
Main template to kick off processing our Sample.xml
From here on we use a simple XPath selection query to
get to our data.
-->
<xsl:template match="/">
<html>
<head>
<title>Welcome to <xsl:value-of select="/company/name"/></title>
<style>
body,td {font-family:Tahoma,Arial; font-size:9pt;}
</style>
</head>
<body>
<h2>Welcome to <xsl:value-of select="/company/name"/></h2>
<p/>
<b>Our contact details:</b>
<br/>
<br/>
<xsl:value-of select="/company/name"/>
<br/>
<xsl:value-of select="/company/address1"/>
<br/>
<xsl:value-of select="/company/address2"/>
<br/>
<xsl:value-of select="/company/city"/>
<br/>
<xsl:value-of select="/company/country"/>
</body>
</html>
</xsl:template></xsl:stylesheet>