Firefox document object lacks DOM properties in XSLT-generated pages

I started working on a keyboard-shortcut library and knew (somewhere in the hidden inaccessible depths of my mind) that I had a problem with document.body property a while ago. As it's required by the HTML DOM standard, I immediately suspected that it was an IE problem ... and chased that ghost for a while, until I've realized how wrong I was.

The buggy browser was Firefox: if you create a web page with local XSLT transformation (dictated by the xml-stylesheet instruction in the XML document returned from the server) in Firefox (up to at least 2.0.0.6), everything looks normal, but document.body is null and document.forms, document.links and other similar array are empty.

To make matters more confusing, all other HTML DOM calls work (it's a different bug from this one), so I had to substitute the links array with document.getElementsByTagName("A") and the body property with the document.getElementsById("body") (and used the id attribute on the body tag).

Testing individual XSLT features

The easiest way to test individual XSLT features is as follows:


  • Install SAXON;

  • Create a small XML document with structure that represents your input data;

  • Create a small XSL stylesheet focusing on features you want to test;

  • Use xml:output method='text' in the test stylesheet to produce the test results without XML garbage;

  • Perform the tests with SAXON;

  • Test the transformation in your target environment. If you're developing browser-side transformations, insert xsl-stylesheet pseudo-instruction in your XML document and open it with Internet Explorer and Firefox.

You can see how I've used this approach in this post.

Handling unexpected children in xsl:apply-templates

When you use xsl:apply-templates in a xsl:template, you might get extra text strings in the transformed results if your input XML data contains unexpected elements with text nodes (due to default XSLT template rules, the extra elements themselves and their attributes are ignored).

There are three ways you can handle this situation:

  • Write an XML schema and validate input data against it before the transformation;
  • List the children you expect in the xsl:apply-templates instruction;
  • Define a low-priority default template the does nothing.
For example, when the input XML document ...
<?xml version="1.0" ?>
<data>
  <a>A1</a>
  <b>B1</b>
  <c>Unexpected</c>
  <b>B2</b>
  <a>A2</a>
</data>
... is processed with the stylesheet ...
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="data">
  <xsl:apply-templates /></xsl:template>

<xsl:template match="a">
  A: <xsl:value-of select="text()" />
</xsl:template>

<xsl:template match="b">
  B: <xsl:value-of select="text()" />
</xsl:template>

</xsl:stylesheet>
... you get the string Unexpected in the transformed results. You could either list the children you expect in the xsl:apply-templates, for example ...
<xsl:template match="data">
  <xsl:apply-templates select="a|b" /></xsl:template>
... or you could define a default template that does nothing (overwriting the built-in default that outputs the child text nodes) ...
<xsl:template match="*" priority="-100" />

This post is part of You've asked for it series of articles.

Another IE bug: transformed plain text displayed as HTML

If you use browser-side XSLT transformation triggered with xsl-stylesheet pseudo instruction in the source XML document and set the output format to plain text with xsl:output method='text', you'd expect the results to be displayed as unformatted text in the browser window (similarly to what browser does when served a document with content-type: text/plain). Not surprisingly, Firefox behaves as expected, but Internet Explorer 7 renders the results as pure HTML (going as far as interpreting the start-of-tag characters).For example, when the following XML document ...
<?xml version="1.0" ?>
<?xml-stylesheet href="t1.xsl" type="text/xsl"?>
<data>
  <row>Sample</row>
</data>
... is transformed with this stylesheet ...
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 
<xsl:output method="text" />

<xsl:template match="row">
&lt;b&gt;<xsl:value-of select="text()" />&lt;/b&gt;
</xsl:template>

</xsl:stylesheet>
... Firefox displays the resulting text (<b>Sample</b>), but Internet Explorer displays Sample.

Yet another reason to use Saxon

Testing a sample stylesheet today, I've discovered that Saxon reports a lot of recoverable errors that are silently ignored by other XSLT implementations (MSXML or Gecko).For example, when faced with this stylesheet ...
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 
<xsl:template match="data">
  <xsl:apply-templates /></xsl:template>
 
<xsl:template match="a">
  A: <xsl:value-of select="text()" />
</xsl:template>
 
<xsl:template match="a">
  B: <xsl:value-of select="text()" />
</xsl:template>
 
</xsl:stylesheet>
... Saxon would report ambiguous rule match (even documenting the input element that caused the error and the source line number), whereas all the other XSLT translators would silently produce "best effort" results. In fact, the stylesheet had a typo, the last template should match the b element and I would have lots of problems detecting that with MSXML (for example).

Why would I use select='text()'

<xsl:value-of select='text() /> is used when you want to select the text embedded between the opening and closing tag of the current element. However, in this context, the text() function selects only the first child text node. If you want to:

  • select all embedded text (including text within the child elements), use <xsl:value-of select='.' /> as this renders the whole tree of descendants as a text string;
  • select all text nodes within the current element but no text in descendant elements, use a <xsl:for-each select='text()' > loop.
For example, the following XML document ...
<?xml version="1.0" ?>
<?xml-stylesheet href="t1.xsl" type="text/xsl"?>
<data>
  <row>Before <b>an embedded tag</b> and after it</row>
</data>
... transformed with this stylesheet ...
<?xml version="1.0" encoding="windows-1250" ?>
<xsl:stylesheet
 version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 
<xsl:output method="text" encoding="windows-1250" />

<xsl:template match="row">
  Text(): <xsl:value-of select="text()" />
  Current element: <xsl:value-of select="." />
  Text loop: <xsl:for-each select="text()"><xsl:value-of select="." /></xsl:for-each>
</xsl:template>

</xsl:stylesheet>
... results in the following text:

Text(): Before
Current element: Before an embedded tag and after it
Text loop: Before and after it

This post is part of You've asked for it series of articles.

XSL: Remove whitespace from source XML document

While searching for a solution to a completely different problem, I've stumbled across a very elegant way to remove whitespaces from input XML documents before they are transformed (see also description of problems caused by them) - use xsl:strip-space instruction, for example <xsl:strip-space elements='*' />

Test for empty attributes in XSLT

Testing for missing attributes in XML elements is different from testing for attributes with empty values. You can test for missing attributes with <xsl:if test="not(@attribute)">, but this test will never succeed if the attribute is present but empty. In that case, you have to use the <xsl:if test="@attribute = ''"> condition.

This post is part of You've asked for it series of articles.

Workaround: generate explicit closing tag in XSLT

It looks like the PHP XSLT functions have a bug when generating HTML output: they generate self-closing <script src="..."/> tags that cause Internet Explorer to hickup, although the XSLT transformation engines should take care of HTML peculiarities (including the set of <script></script> tags) when you set xsl:output to html.

The workaround provided in PHP documentation comes handy in any situation where you want to have an explicit closing tag for whatever reason. Instead of <tag></tag> which is usually output as <tag />, your XSLT transformation should contain <tag><xsl:comment /></tag>, which will generate the opening and closing tag.

Output XML data from ASP

These are the steps you need to take to output XML data from ASP script:

  • Clear the output buffer to ensure no HTML tags are sent to the client;
  • Set the content-type to text/xml;
  • Optionally (but highly recommended) set the character set to utf-8 and change the ASP code page;
  • Output the XML data (for example, writing a DOM object xml property to the output stream);
  • Stop ASP script processing.

The sample ASP code is included below and you can get more in-depth description of the necessary operations in my InformIT article Optimized presentation of XML content.

Response.Clear
Response.ContentType = contentType
Response.Charset = "utf-8"
Response.Codepage = 65001
Response.Write txt
Response.End

Note: this post is part of You've asked for it series of articles.

Converting forms to AJAX

Form submission handling is probably one of the more challenging topics if you've decided to deploy an AJAX application instead of a traditional page-by-page web application. In his short article, Kris Hadlock has provided an excellent sample code that you can deploy to transform a form submission request into an AJAX request (thus retaining tight control over the results and error handling).

How to avoid common CSS mistakes

I admit it - I was also one of those web developers that jumped in CSS waters with helping hand of uncle Google instead of a good introductory and reference book on the topic. If you want to avoid some of the stupidities I've been doing, read the Seven Common CSS Mistakes and How to Avoid Them article I wrote for InformIT.

Using transformNode in IE7

Apparently a lot of people land on my blog when using Google to figure out how to use transformNode function in IE7. The answer is simple - you don't do it, as it's IE-only function that will obviously not work in any other browser.

What you should do instead is to use a wrapper library like Sarissa that gives you XSLTProcessor object in both Firefox and Internet Explorer environments. The XSLTProcessor API is described in Mozilla documentation (which also includes a simple example).

Client-side development environment

Scenario: XSLT deployment in a browser/server scenario with XSLT transformations performed on the browser (JavaScript or with <?xsl-stylesheet ?>)

Potential tools:

  • Saxon is great for off-line testing (primarily while developing small bits of code or trying new programming techniques). It cannot fetch the information from the server, so you have to provide test data in local XML files
  • Firefox is the best tool if you want to test client-server integration and use <?xsl-stylesheet ?> approach as it can recover from XSLT errors (which IE can't). However, it doesn't detect all errors, so the stylesheets working with Firefox might break in IE (but not due to an IE bug)
  • IE is a nightmare when using <?xsl-stylesheet ?> directive. Whenever something breaks (error in stylesheet or even server-side error resulting in HTML response instead of XML response), its cache gets messed up and you have to restart the browser to continue the tests. I therefore use IE only in the final tests to verify that my XSLT has no weird errors not detected by Firefox.
  • The best testing mechanism is probable the manual (JavaScript) client-side transformation. You can do it in IE or Firefox; in this case I would prefer IE, as it has better XSLT error reporting (MSXML is not that bad :).

Example: Use XSLT transformation in browser

Several readers were asking for an code sample that performs XSLT transformation in the browser, so here it is :) To start with, you should use a wrapper library to isolate yourself from browser version/platform inconsistencies. I'm using Sarissa to deal with XML, XSLT and HttpRequest and X library to deal with DHTML-related functions.

The most common XSLT-related operation that you do in your browser is this:

  • Download XML document from the web server using XMLHttpRequest;
  • Transform the XML into application-specific HTML markup with an XSLT transformation;
  • Insert the resulting HTML markup into the web page.

Sarissa library has a function (Sarissa.updateContentFromURI) that does almost exactly what you need to get there, so you only need to perform the following steps:

  • Load the XSLT stylesheet as XML document (sync load is easier to do).
  • Import the loaded XML document into an XSL processor (special object that can perform the XSLT transformations).
  • Call the updateContentFromURI function.

The resulting code is very simple:

// load XSLT stylesheet, done only once.
var xsl = loadURI("moveRoutes_lists.xsl");
if (!xsl) throw("Cannot load XSL stylesheet");

var xform = new XSLTProcessor();
xform.importStylesheet(xsl);

// the following call transforms a remote XML document
// into HTML fragment and inserts it into the target
// element
Sarissa.updateContentFromURI(remoteURI, xGetElementById(targetElement),xform);

Notes:

  • sarissa.js as well as sarissa_dhtml.js libraries have to be included in the source document.
  • xGetElementById function is part of the X library.
  • loadURI function is documented here.