C#中如何將XML+XSL文檔轉換為HTML格式

來源:互聯網
上載者:User

   最近一直在寫一個小工具,可以將自己儲存在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

            }

    }

   }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.