XSLT transform and XUI injection using JavaScript

Submitted by: Clay Helberg Last Updated: 2007-08-01

Clay Helberg demonstrates how to perform an XSLT transform of an XML document (e.g. a response from a web service) and inject the result in an XUI dialog. This is done using the Java package functionality of Rhino (the JavaScript engine included with Arbortext Editor)

// assume: //   querydoc is the XML returned by the server //   xslname is the URL of the XSLT stylesheet //   xuicontrol is the XUI dialog document into which you want to insert the transformed content // set up inputs and outputs for transformation domSource = Packages.javax.xml.transform.dom.DOMSource(querydoc); stylesheet = Packages.javax.xml.transform.stream.StreamSource(xslname); domResult = Packages.javax.xml.transform.dom.DOMResult; // set up transformer tfactory = Packages.javax.xml.transform.TransformerFactory.newInstance; transformer = tfactory.newTransformer(stylesheet); // do the transform transformer.transform(domSource,domResult); newdoc = domResult.getNode; // copy results into XUI control; function is defined below copyContents(newdoc,xuicontrol); function copyContents(fromnode,tonode) { // function to copy contents, since Arbortext's // insertNode function doesn't seem to grok plain vanilla // DOM DocumentFragments (d'oh!) // copy each child node for (var i=0; (kid = fromnode.childNodes.item(i)); i++) { switch (kid.nodeType) { case 1: // element node // copy the node var newnode = tonode.ownerDocument.createElement(kid.nodeName); // copy attributes, if any for (var j=0; (attr = kid.attributes.item(j)); j++) { newnode.setAttribute(attr.nodeName,attr.nodeValue); }       // drill down if this node has descendants copyContents(kid,newnode); tonode.appendChild(newnode); break; case 3: // text node tonode.appendChild(tonode.ownerDocument.createTextNode(kid.nodeValue)); break; }  } }

Note that you'll have to beef up the copyContents function if your server XML includes things like namespaces, processing instructions, and other stuff that isn't plain elements or text.

It might be easier to do this in a java class and then just invoke a method on your java class from the script. I haven't tried it, but doing it that way might avoid the ClassCastExceptions I was getting trying to insert a W3C DocumentFragment into an Arbortext ANode or ARange in javascript. In that case, you could dispense with the copyContents function.

=Related content=

Simpler XSLT transform and XUI injection using JavaScript