Wednesday, April 04, 2007

XSLT and Boolean Element Value Tests

In my most recent project, the engineers spitting out the XML have a bad habit of inconsistently filling in boolean values. I never know if one of my elements is going to have:  y  n  Y  N  yes  no  Yes  No  t  f  T  F  true  false  True   False

So the two functions you need to deal with this are substring() to only look at one character, and some form of lowercase() or tolower() function.  However, xslt 1.0 by itself doesn't have that, but you can get around it using the translate() method.  With translate you have to specify the characters to swap out, much like the unix 'tr' command:  /ABC/abc/ sort of thing.

Luckily we don't have to worry about the entire alphabet here, just a couple of characters.  And while you're at it you can merge the truefalse into yesno as well.  Try this next time you need to test a boolean value:

<xsl:if test="translate(substring(MyElement,1,1),'YNTFtf','ynynyn')='y'>  <!--  Do the true case..... ->

You're taking the first letter (which can be one of y,n,Y,N,t,f,T,F) and translating it into either y or n, depending.  There's nothing in translate that says you can't translate T into y if you really want to!  Notice too that 'yn' is not represented in the first half of what to translate, because those are fine like they are.  But YN translates to yn, TF to yn, and tf to yn.

Or even better you could go back to whoever is producing the XML and tell them to get with the program and pick a boolean scheme and stick with it. :)

Technorati tags:


Anonymous said...

Too bad XSLT doesn't suport regex. Here is how I handle it in PERL:

sub isAffirmative(){
my ($s) = @_;
if (!$s or $s eq ""){
return 0;
if ($s =~ /^yes|y|full|on|true|t|(?:[0-9]*[1-9][0-9]*)|sure|affirmative|yeah|absolutely$/i){
return 1;
return 0;


JHardin said...

Don't forget 1/0!