昨天花了点时间学习了一下XSLT,然后就想到自己可以做个Demo,不想竟遇到不少问题,而且花了很长时间在网上查找资料。索性分享出来,希望能帮别人节省点时间。

      下面的例子是在空白页面上加载一个格式化后的XML文件,我分别作了JavaScript和ASP.NET两个版本。

      使用JavaScript操作XSLT比较简单,就是要分浏览器,而且如果是IE还要看XML解析器的版本。我用了最近但的方法写:)

    <script type="text/javascript">
        var xml = new ActiveXObject("Microsoft.XMLDOM");
        xml.async = false;
        xml.load("cdcatalog.xml");

        var xsl = new ActiveXObject("Microsoft.XMLDOM");
        xsl.async = false;
        xsl.load("cdcatalog.xsl");

        document.write(xml.transformNode(xsl));
    </script>

  使用ASP.NET来做就是利用XslCompiledTransform类,但是选择转换函数的哪一个重载版本有些讲究:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            XmlDocument xml = new XmlDocument();
            xml.Load(Server.MapPath("cdcatalog.xml"));
            XslCompiledTransform xsl = new XslCompiledTransform();
            xsl.Load(Server.MapPath("cdcatalog2.xsl"));

            xsl.Transform(xml, null, Response.OutputStream);
            
        }
    }

  我看到很多人都是利用先输出到物理文件或者利用MemoryStream来做中间过渡,然后再调用Response.Write(...)写入到页面。其实直接向Reponse.OutputStream流写就行。

 

相关文章:

  • 2021-10-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-15
  • 2022-01-23
猜你喜欢
  • 2022-03-11
  • 2021-09-20
  • 2022-12-23
  • 2021-08-14
  • 2021-06-16
  • 2021-05-18
  • 2022-12-23
相关资源
相似解决方案