This Java program makes use of a Ternary if, to map booleans to output strings: (a "*" for true, an empty string for false).
public class ternary {
public static void main(String[] args) {
boolean flags[]={true,false,true};
for (boolean f : flags) {
System.out.println(f?"*":"");
}
}
}
So the output is *, [empty], *.
I have an input XML document, something like:
<?xml version="1.0" ?>
<?xml-stylesheet type="text/xsl" href="change.xsl"?>
<root>
<change flag="true"/>
<change flag="false"/>
<change flag="true"/>
</root>
And I have the following XSLT template which maps true to '*' and false to '' (it works):
<xsl:template match="change">
<xsl:variable name="flag" select="translate(substring(@flag,1,1),'tf','*')"/>
<xsl:value-of select="$flag"/>
</xsl:template>
Is there is more concise version of this ?
a) Can I automatically get a value of boolean true|false directly from the string 'true|false' ? b) Is there an (xpath?) construct to map the boolean true|false to '*', '' ?
You could utilise simple pattern matching in templates for this.
So, the first one matches true entries, and the other one matches all other cases (which in your cases is just false
So, given the following stylesheet
When applied to your sample XML, the following is output
This is actually an XPath question.
I. XPath 1.0
There are more than one XPath expressions the evaluation of which produces the wanted result:
This also answers b) -- notice that the strings
'true'
and'false'
aren't boolean values! The only two boolean values aretrue()
andfalse()
and they are not strings.In the above expression we use the fact that in XPath 1.0 if a boolean is in a context where a number is needed, it is automatically converted to number. By definition:
number(true())
is1
and
number(false())
is0
Thus the second argument of the call to
substring()
above:is evaluated as
1
when@flag = 'true'
and to2
otherwise.A more general XPath 1.0 expression that produces the string
$s1
if$val
is"x"
and produces the string$s2
if$val
is"y"
:This produces the string
$s1
when$val = "x"
, the string$s2
when$val = "y"
, and the empty string -- if none of these two conditions holds.The above XPath 1.0 expression can be generalized to produce N different string results
$s1
,$2
, ...,$sN
exactly when$val
is one of the values$v1
,$v2
, ...,$vN
because the functionconcat()
can have any number of arguments.II. XPath 2.0 (XSLT 2.0)
And more generally, given 2*N atomic values
$s1
,$s2
, ...$sN
and$v1
,$v2
, ...,$vN
, such that all$vi
values are different, the result of evaluating this XPath 2.0 expression:is
$sK
exactly when$v eq $vK
.