XSLT Tricks

Curly Brackets and Dollar Signs

When you want to generate the expression ${property.key} with XSLT and you simply write this in the template, XSLT will interpret the curly brackets as an XPath Expression and will print out the value it calculates. It will fail silently and the output just shows $ having evaluated {property.key} to an empty string.

The trick is to use double curly brackets as shown in the listing below. It will evaluate the expression in the first curley brackets pair which is an curly brackets expression getting returned as a string.

<!-- evaluates to $ -->
<xsl:template match="...">
${property.key}
</xsl:template>

<!-- evaluates to ${property.key} -->
<xsl:template match="...">
${{property.key}}
</xsl:template>

Adding types to variables

You can add types to variables in your stylesheet. This allows for better error messages as these types are checked during execution.

<!-- variable with dynamic type -->
<xsl:template match="...">
     <xsl:variable name="var1" select="..." />
</xsl:template>

<!-- variable with static type string -->

<xsl:template match="...">
     <xsl:variable name="var1" select="..." as="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" />
</xsl:template>

More information and other cool tricks for making XSLT2 safer can be found at http://www.ibm.com/developerworks/library/x-safexslt/

Advertisements

Initializing Arrays in Java

Arrays are widely used in many (almost any) programming languages. In Java, you have to specific the length of an Array at the creation of an Array.

Here is a short example how to initalize an Array containting the numbers 1, 2 and 3:

int[] numbers = new int[3];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;

In order to abbreviate this, there is a short form which can do this work in one line. This works as Java can determine the length of the array by looking at the number of elements within the curly brackets. At compile time, the short form is translated to the form above within the byte code.

int[] numbers2 = {1,2,3};

Now, there are some quirks to be aware of regarding the short form. You can use this only while defining the array variable. The following will result in a compile error:

int[] numbers2 = {1,2,3};
numbers2 = {4,5,6}; // compile error!

Why does this happen? The error message says: “Array constants can only be used in initializers”. But I am not quite sure, what the meaning behind is. I consider it a quirk of the Java language without any further research regarding this construct. 😉

However, today, I found a trick to circumvent this issue. You can find the solution in the Oracle Java Magazine, Section Fix This.

int[] numbers3 = {1,2,3};
numbers3 = new int[]{4,5,6};

I am not quite sure, why this works. Do you?