Call XSLT file from data:text/xml

前端 未结 1 1822
谎友^
谎友^ 2021-01-27 22:49

Have a nice day everybody

i\'m trying to call a XSLT file from an XML that i\'m rendering using data:text/xml, obtained from a REST. The most basic attempt is to use thi

相关标签:
1条回答
  • 2021-01-27 23:20

    As this is client-side Javascript inside of web browsers like Firefox or Chrome I would suggest to use XSLTProcessor to perform the XSLT transformation, you can pull in the XSLT stylesheet using XMLHttpRequest, parse your responseData using DOMParser and then you can use XSLTProcessor for the transformation.

    I don't think you will get the browser to execute an XSLT referenced in the data URL, unless the XSLT is embedded itself as data:

    var encodedXslt = 'data:application/xml,' + encodeURIComponent(document.getElementById('xslt').textContent);
    
    
    var xmlCode = document.getElementById('xml').textContent;
    var pi = '<?xml-stylesheet type="text/xsl" href="' + encodedXslt + '"?>';
    
    var encodedXml = 'data:application/xml,' + encodeURIComponent(pi + xmlCode);
    
    window.frames.xmlDisplay.location.href = encodedXml;
    <script id="xslt" type="application/xml+xslt">
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
      <xsl:output method="html" indent="yes"/>
      <xsl:template match="list">
        <ul>
          <xsl:apply-templates/>
        </ul>
      </xsl:template>
      <xsl:template match="item">
        <li>
          <xsl:apply-templates/>
        </li>
      </xsl:template>
    </xsl:stylesheet>
    </script>
    
    <script id="xml" type="application/xml">
      <list>
        <item>foo</item>
        <item>bar</item>
      </list>
    </script>
    
    <iframe name="xmlDisplay" width="100%" height="300"></iframe>

    However, it seems only Mozilla swallows that attempt and applies the XSLT, Chrome continues to complain about an unsafe attempt. So I think it is better and more portable to implement any XSLT transformation where you have the input as a Javascript string with XSLTProcessor.

    0 讨论(0)
提交回复
热议问题