Firefox document object lacks DOM properties in XSLT-generated pages
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
- 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.
<?xml version="1.0" ?>... is processed with the stylesheet ...
<data>
<a>A1</a>
<b>B1</b>
<c>Unexpected</c>
<b>B2</b>
<a>A2</a>
</data>
<?xml version="1.0" ?>... 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: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>
<xsl:template match="data">... or you could define a default template that does nothing (overwriting the built-in default that outputs the child text nodes) ...
<xsl:apply-templates select="a|b" /></xsl:template>
<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
<?xml version="1.0" ?>... is transformed with this stylesheet ...
<?xml-stylesheet href="t1.xsl" type="text/xsl"?>
<data>
<row>Sample</row>
</data>
<?xml version="1.0" ?>... Firefox displays the resulting text (<b>Sample</b>), but Internet Explorer displays Sample.
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:template match="row">
<b><xsl:value-of select="text()" /></b>
</xsl:template>
</xsl:stylesheet>
Yet another reason to use Saxon
<?xml version="1.0" ?>... 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).
<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>
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.
<?xml version="1.0" ?>... transformed with this stylesheet ...
<?xml-stylesheet href="t1.xsl" type="text/xsl"?>
<data>
<row>Before <b>an embedded tag</b> and after it</row>
</data>
<?xml version="1.0" encoding="windows-1250" ?>... results in the following text:
<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>
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
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
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
How to avoid common CSS mistakes
Using transformNode in IE7
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.
