Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control boolean rendering in xslt

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.

like image 750
Filburt Avatar asked Aug 17 '11 08:08

Filburt


People also ask

What is ETV and XTT in XSLT?

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.

Can we reassign a value to variable in XSLT?

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.

What are the various steps in XSLT processing?

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.


1 Answers

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>
like image 101
Dimitre Novatchev Avatar answered Sep 17 '22 15:09

Dimitre Novatchev