XSLT Variable Arrays

I recently answered a question on a popular programmers forum about how to store and access an array of user-defined variables in a stylesheet and then loop though those variables. I realized that many developers are not familar with the available techniques for doing this and decided to add an entry in my blog about this topic.

User-defined variable arrays within stylesheets are not part of the XSLT specification. The usual way to handle this problem in XSLT 1.0 stylesheets is to define a user-defined top-level element which belongs to a non-null namespace which is different from the XSLTnamspace. These user-defined top-level elements are typically used to store error messages, lookup data, etc. You can then access these user-defined elements from within your stylesheet by treating the stylesheet as an additional source document and loading it using the document() function with an empty string as the first argument. An empty string is interpreted to mean the current stylesheet.

If you are using XSLT 2.0, this method is no longer needed as simpler and more elegant methods are available to us. For example, you can store and directly access the variables using the <xsl:variable> element as shown in the following stylesheet.

You may be wondering about this image. It is from the screen of my laptop. I used xsltproc on Microsoft Vista SUA for the XSLT 1.0 transformation and Saxon 9 in Microsoft Powershell v2.0 CTP2 for the two XSLT 2.0 transformations.

Note that the XSLT 1.0 method described above still works in XSLT 2.0.&nbsp If stylesheet portability is an issue for you, I suggest you continue to use this method.