準備原始XML檔案,如Person.xml:
<?xml version="1.0" encoding="utf-8" ?><?xml-stylesheet type="text/xsl" href="Person.xslt" ?><xmlRoot> <PersonInfo> <Name>Adam</Name> <Adress>湖南長沙</Adress> <Gender>男</Gender> </PersonInfo> <PersonInfo> <Name>Eva</Name> <Adress>湖南長沙</Adress> <Gender>女</Gender> </PersonInfo></xmlRoot>
準備xslt檔案,如Person.xslt檔案:
此處有幾點說明xsl:output節點的 method 屬性可以指定輸出的格式如html,xml,text等,這裡指定輸出為html
<?xml version="1.0" encoding="utf-8"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"> <xsl:output method="html" indent="yes" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/> <xsl:template match="/"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> <title>Elfin – Daily Report</title> <style type="text/css"> table { border: 1px solid black; border-collapse: collapse; } table thead tr th { border: 1px solid black; padding: 3px; background-color: #cccccc; } table tbody tr td { border: 1px solid black; padding: 3px; } </style> </head> <body style="font-family: Tahoma, Verdana, Helvetica;"> <table > <tr> <td>姓名</td> <td>地址</td> <td>性別</td> </tr> <xsl:for-each select="/xmlRoot/PersonInfo"> <tr> <td> <xsl:value-of select="Name"/> </td> <td> <xsl:value-of select="Adress"/> </td> <td> <xsl:value-of select="Gender"/> </td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template></xsl:stylesheet>
C#的轉碼:
XmlDocument XmlDoc = new XmlDocument(); XmlDoc.Load("Person.xml");//原始xml文檔 Stream stream = File.Open("Person.xslt", FileMode.Open); XPathDocument xslDoc = new XPathDocument(stream);//xpath文檔 XslCompiledTransform xslt = new XslCompiledTransform(true);//Transforms XML data using an XSLT style sheet MemoryStream outStream = new MemoryStream(); xslt.Load(xslDoc); xslt.Transform(XmlDoc, null, outStream); StringBuilder sb = new StringBuilder(HttpUtility.HtmlEncode(Encoding.UTF8.GetString(outStream.GetBuffer()))); string html = sb.Replace("<", "<").Replace(">", ">").Replace(""", "\"").Replace("&", "&").Replace("\u0000", "").ToString();