C#中如何将XML+XSL文档转换为HTML格式

   最近一直在写一个小工具,可以将自己存储在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

            }

    }

   }

 

posted on 2011-08-30 17:54  halia  阅读(1597)  评论(0编辑  收藏  举报