Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT not working in web browser

Tags:

browser

xml

xslt

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?

like image 344
lanicor Avatar asked Apr 29 '15 10:04

lanicor


2 Answers

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:

enter image description here

like image 184
kjhughes Avatar answered Nov 04 '22 11:11

kjhughes


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.

like image 3
Michael Kay Avatar answered Nov 04 '22 11:11

Michael Kay