最近一直在寫一個小工具,可以將自己儲存在xml檔案中的內容通過outlook郵件發送出來,在做的過程中發現在發送郵件的時候,body的內容不能通過讀取xml資料的方式直接發送出來,但是可以通過html的格式發送出來(設定message.IsBodyHtml= true), 所以就想找個辦法將xml檔案轉換成html檔案。
在網上調查的過程中看到了很多人講了如何將html檔案轉化為xml檔案,在查到xml轉化為html的時候多數提到了XslCompiledTransform類,於是我就用了XslCompiledTransform類,代碼如下:
using System.Xml;
using System.Xml.Xsl; //使用XslCompiledTransform 類必須添加的命名空間
using System.Xml.XPath;
namespace Magci.Test.XML.TestXsl
{
class Program
{
static void Main(string[] args)
{
XslCompiledTransform xslt = new XslCompiledTransform ();
xslt.Load(xslFile); //Load方法載入樣式表,xslFile代表要載入的xslt樣式表,如books.xsl
XPathDocument xDoc = new XPathDocument(xmlPath); //使用指定檔案中的XML資料進行初始化,如books.xml
XmlTextWriter xtWriter = new XmlTextWriter(htmlFile, null); //使用指定檔案中建立XmlTextWriter類的執行個體,htmlFile就是要寫入的檔案。如果該檔案存在,就截斷該檔案並用新內容對其進行改寫,如books.html ,第二個參數是產生的編碼方式。如果為空白,則用UTF-8形式寫出該檔案。
xslt.Transform(xDoc, xtWriter ); //Transform方法是實現格式轉換,使用指定的輸入文檔執行轉換,然後結果輸出到XmlTextWriter
xtWriter .Close(); //Write the XML to file and close the writer
}
}
}