To conform with the <boolean>
spec of Xml-RPC I need to transform my xs:boolean
from true|false
to 1|0
.
I solved this using xsl:choose
<xsl:template match="Foo">
<member>
<name>Baz</name>
<value>
<boolean>
<xsl:choose>
<xsl:when test=".='true'">1</xsl:when>
<xsl:otherwise>0</xsl:otherwise>
</xsl:choose>
</boolean>
</value>
</member>
</xsl:template>
but was wondering if there is a less brittle way of controlling how boolean values are rendered when transformed with xslt 1.0.
Element Transformation & Validation (ETV / XTT)IntroductionThe Element Transformation and Validation (ETV) step transforms and validates the elements within an XML document as instructed by attributes attached to those elements.
Variables in XSLT are not really variables, as their values cannot be changed. They resemble constants from conventional programming languages. The only way in which a variable can be changed is by declaring it inside a for-each loop, in which case its value will be updated for every iteration.
xsl:apply-imports, xsl:apply-templates, xsl:attribute, xsl:call-template, xsl:choose, xsl:comment, xsl:copy, xsl:copy-of, xsl:element, xsl:fallback, xsl:for-each, xsl:if, xsl:message, xsl:number, xsl:processing-instruction, xsl:sort, xsl:text, xsl:value-of, xsl:variable.
Use:
number(boolean(.))
By the definition of the standard XPath function number()
it produces exactly {0, 1}
when applied, respectively, on {true(), false()}
Beware! If you use this construction on strings, the result will be true for both 'false' and 'true', because, for string parameters, boolean() is true if and only if its length is non-zero.
So, if you want to convert strings, not booleans, then use this expression:
number(not(. = 'false'))
Below is an XSLT-based verification:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="number(not(. = 'false'))"/>
</xsl:template>
</xsl:stylesheet>
when this transformation is applied on the following XML document:
<t>
<x>true</x>
<y>false</y>
</t>
the wanted, correct result is produced:
<t>
<x>1</x>
<y>0</y>
</t>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With