xslt好像样式可以把数据转换成不同的格式,像xml,html等,在C#中提供了简单的方式使用xslt。
1.首先引用名字空间
System.Xml
System.Xml.XPath
System.Xml.Xsl
2.加载xml作为源
XPathDocument myXPathDoc = new XPathDocument("xml路径");
3.加载xsl,转换规则
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load("xsl路径");
4.声明一个输出目标
XmlTextWriter myWriter = new XmlTextWriter("输出文件","Encoding") ;
5.转换
myXslTrans.Transform("源文件","目标文件");
一个完整的demo:
public void XslTrans()
{
//step1:load xml file via XpathDoucment
XPathDocument xdoc = new XPathDocument("c:/demo.xml");
//step2:load xsl file via XslTransform
XslCompiledTransform trans = new XslCompiledTransform();
trans.Load("c:/demo.xsl");
//step3:create output stream via XmlTextWriter
XmlTextWriter xtw = new XmlTextWriter("c:/demo.html", Encoding.UTF8);
//step4:transform
trans.Transform(xdoc, null, xtw);
xtw.Close();
}
------------------------------------------------------------------------------------------------------------------------------------
demo.xml
------------------------------------------------------------------------------------------------------------------------------------
<company>
<name>XYZ Inc.</name>
<address1>One Abc Way</address1>
<address2>Some avenue</address2>
<city>Tech city</city>
<country>Neverland</country>
</company>
------------------------------------------------------------------------------------------------------------------------------------
demo.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>
------------------------------------------------------------------------------------------------------------------------------------