How to control boolean rendering in xslt

2019-06-15 14:47发布

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.

1条回答
The star\"
2楼-- · 2019-06-15 15:11

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>
查看更多
登录 后发表回答