XSLT not working in web browser

2020-03-30 05:44发布

问题:

I have an XSLT file for styles in XML. The XSLT is accessible via a URL (http://someurl/somefile.xsl) without problems.

When I insert the same URL into an xml-stylesheet processing instruction, it only renders plain text in browsers (FF, IE),

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="http://someurl/somefile.xsl"?>
<rootElement>...</rootElement>

but when I use a local file path (file downloaded to same folder as the XML file), it works like a charm:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="somefile.xsl"?>
<rootElement>...</rootElement>

Why?

回答1:

Running XSLT in a Web Browser

Running XSLT in the browser is subject to some limitations:

  • XSLT 2.0 is not supported by any of the major web browsers.

  • Browser security models differ regarding XSLT processing.

    • Cross-domain restrictions will often require that the XSLT load from the same origin as the the XML. (This appears to be biting you in this case.)

    • Chrome does not allow locally loaded XSLT to run (even when the XML is locally loaded). This can be annoying during development.

For these reasons, XSLT is more often run on the server or in batch mode rather than in the browser.

If you wish to run XSLT in the browser and have it work with Chrome, Firefox, and IE, you must

  1. Use XSLT 1.0 only, not XSLT 2.0.
  2. Use an xml-stylesheet processing instruction in the XML file as you've done to link the XSLT file with the XML file:

    <?xml version="1.0" encoding="UTF-8"?>
    <?xml-stylesheet type="text/xsl" href="http://origin-domain/path/to/file.xsl"?>
    <rootElement>...</rootElement>
    
  3. Serve the XSLT from a server, not from a local file.
  4. Make sure that the XSLT originates from the same domain as the XML.

Finally, be sure to check the browser console for any error messages. For example, here's what IE shows when the XSLT cannot be located:



回答2:

Since this answer is being linked to from other questions, I will add an update: it is now possible to run XSLT 3.0 stylesheets in the browser using the Saxon-JS implementation. This lifts many of the limitations present with the built-in XSLT processors that come with the various browsers.



标签: xml xslt browser