Accessing XML and XSLT Documents from Script
The HTML that results from browsing XML with an XSLT style sheet is fully scriptable using the Dynamic HTML (DHTML) Object Model. In addition, there are two properties available on the DHTML document
object that provide script access to the XML and XSLT documents.
The
document.XMLDocument
property returns the root node of the XML source document.The
document.XSLDocument
property returns the root node of the XSLT style sheet document.
Modifications to these two documents through the DOM do not automatically cause updates to the resulting HTML tree, but rather offer a hook that you can use to wire up the specific updates you need.
Consider the following example, which shows how the menu is dynamically sorted in the restaurant review XSLT sample, review.xsl. First, add the links that trigger sorting to the style sheet.
<P class="tagline">
<A href="javascript:sort('price')">Sort menu by price</A>
<A href="javascript:sort('description')">Sort menu by description</A>
</P>
Next, write the sort
function to apply the sort to the menu data and update the display. The script accesses the DOM for the XSLT style sheet with the XSLDocument
property, and uses DOM calls to change attributes representing sort keys.
The XMLDocument
is used to locate the XML source fragment that will be used in the update. Calling transformNode
on the fragment will result in a string of HTML that can be pasted back into the HTML document, as whon in the following JScript code.
function sort(key) {
// Find the "xsl:sort select" attributes in the style sheet.
var s = document.XSLDocument.selectNodes(
"*/xsl:template[@match='menu']//xsl:apply-templates/xsl:sort/@select");
// Replace the values with the new sort key.
for (var i = s.nextNode(); i != null; i = s.nextNode())
{
i.value = key;
}
// Find the subset of the document we need to update.
var d = document.XMLDocument.selectSingleNode("story/menu");
// Apply the style sheet to the subset, and update the display.
document.body.innerHTML = d.transformNode(document.XSLDocument);
}
In this example, the style sheet is modified to generate a different view of the XML. The same mechanisms can be used to change the XML source data and to generate updated views of this data.