How to control boolean rendering in xslt

跟風遠走 提交于 2019-12-23 07:42:17

问题


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:


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>


来源:https://stackoverflow.com/questions/7089712/how-to-control-boolean-rendering-in-xslt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!