How to loop through an array in XSL

If you’re familiar with XSL, you’re probably thinking: “There ARE no arrays in XSL!” Yes, it’s a travesty. But last week at work, while programming in XSL, I desperately needed to loop through an array. Through Googling, I was able to arrive at some alternative functionality that accomplished what I needed.

I was making a template that would take a string of text and return a div in which every other word was a different color. The website I was making a template for had implemented this style by manually wrapping every other word in tags. (Behind-the-scenes CSS took care of the rest.)

I knew exactly how I could accomplish this in JavaScript:

I would split the string into an array of words, loop through the array, and wrap every other word in tags. Then I would put the array back together as a string and return it. Easy!

XSL offered limited possibilities in comparison. Instead of arrays, it had something called sequences which consisted of existing nodes (rather than copies of the node, importantly). But discovering the tokenize function was a game-changer: I could input a string and a separator (such as a space), and the function would return a sequence of every word in the string (since I had split the string by spaces).

Best of all, the sequence was not a copy of the nodes–I could modify the very nodes themselves with a for-each loop on the tokenized sequence!

Behold the final code:

After tokenizing the string, I looped through each word and wrapped every other word in tags. Just like in the JavaScript, I determined “every other” word with the modulus operator. In the JavaScript, I checked for an even index, and in the XSL, I checked for an odd position. Why the difference? JavaScript is zero-indexed, but XSL indices start at one!

XSL has been classified as not a full functional programming language (though the website linked actually refutes this claim) and has limitations compared to other languages, such as JavaScript–but that’s part of what makes it fun and challenging!