Extract the default stylesheet from the DOM document

If you use XSLT transformations to change the XML data into HTML markup and use the xml-stylesheet processing instruction to specify the default XSLT stylesheet to use for the transform, you might need to fetch the default stylesheet value in JavaScript when developing AJAX applications.

You can find a good case study on using XML and XSLT in my Inform-IT article Optimized Presentation of XML Content.

The following JavaScript function extracts the default XSLT stylesheet from the XML document (passed to the function as DOM Document object). It relies on the fact that the DOM Document object extends the Node object and thus has the childNodes property that contains the root element as well as all processing instructions.

function getXMLStylesheet(dom) {

var topNodes = dom.childNodes;

for (var i = 0; i < topNodes.length; i++) {

var node = topNodes[i];

if (node.nodeType == 7) {

if (node.target == "xml-stylesheet") {

var match = /href="(.*?)"/gi.exec(node.data);

if (match.index >= 0) return match[1];





A typical usage of this function is illustrated below:
<script src="/sarissa.js"></script>



var xrq = new XMLHttpRequest();



if (xrq.status == 200) {

var dom = xrq.responseXML;

var xsl = getXMLStylesheet(dom);



No comments:

Post a Comment