Frequently Asked Questions About XSLT

How can I use quoted strings inside an attribute value?

If you need to include a quoted string inside an attribute value (in a select expression, for example), you can use the single quotation mark character (') in the value of the attribute. For example:

How do I choose when to use xsl:for-each and when to use xsl:apply-templates?

The way xsl:for-each and xsl:apply-templates select nodes for processing is identical. The way these instructions find the templates to process the selected nodes is different.

With xsl:for-each, the template to use is fixed. It is the template that is contained in the body of the xsl:for-each element. With xsl:apply-templates, the XSLT processor finds the template to be used for each selected node by matching that node against the template rules in the stylesheet.

Finding a template by matching requires more time than using the contained template. However, matching allows for more flexibility. Also, matching lets you avoid repeating templates that might be used in more than one place in a stylesheet.

Named templates are another option for invoking a template from more than one place in a stylesheet, when you know which template you want. It is a common mistake to use (and bear the overhead of) matching when it is not needed. But it allows you to do powerful things. Matching can take into account the following:

l Pattern matching on the node
l Precedence of templates based on stylesheet importance
l Template priority
l Template ordering

Most complex document-formatting stylesheets use xsl:apply-templates extensively.

How can I insert JavaScript in my result document?

If you want your result document to contain JavaScript commands, you must properly escape the JavaScript code. Use the following format in your XSLT template:

However, this method does not work when your JavaScript section contains a block of XSLT code. In this case, enclosing the JavaScript in a CDATA tag causes the XSLT processor to ignore not just the JavaScript but also the markup code within that tag.

In this situation, enclose the entity reference within an <xsl:text> tag with disable-output-escaping set to "yes". For example:

You can use this wherever an entity reference needs to be handled specifically, as opposed to being handled as part of an entire JavaScript section.

My browser does not understand the tag <br/>. How can I output just <br>?

Although your XSLT stylesheet must contain valid XML (meaning all tags must be either empty or have a closing element), you can instruct the XSLT processor to generate output compliant with HTML. See Deleting Templates.

Alternative: To ensure that your stylesheet always generates correct HTML, specify the xsl:output instruction with the method attribute set to html. See xsl:output.

 
Free Stylus Studio XML Training: