Home > Enterprise >  Creating function from choose statement
Creating function from choose statement

Time:01-31

I have the following choose statement in my xml document

         <xsl:choose>
                  <xsl:when test="number($data)">
                     <xsl:value-of select="concat($data,$percentageSymbol)" />
                  </xsl:when>
                  <xsl:otherwise>
                     <xsl:value-of select="$data" />
                  </xsl:otherwise>
          </xsl:choose>

and the XML document header is :

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" version="1.0" exclude-result-prefixes="fo">

How can I create a function which accepts 2 parameters and does the same logic as the xsl:choose statement?

CodePudding user response:

In XSLT 3.0 you could write

<xsl:function name="f:do-it" as="xs:string">
  <xsl:param name="data" as="xs:string"/>
  <xsl:param name="percentageSymbol" as="xs:string"/>
  <xsl:sequence select="$data || $percentageSymbol[number($data)]"/>
</xsl:function>

(Are you sure you want test='number($data)'? That converts $data to a number and then tests whether the number is not zero and not NaN, which seems a slightly strange thing to do. If you're trying to test whether $data is numeric, then you've got it wrong.)

CodePudding user response:

It appears you're targeting . If your XSLT processor supports (xsltproc does, among others) you can use func:function and func:result, for example:

<xsl:transform version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:func="http://exslt.org/functions"
  xmlns:my="urn:so70882409:local"
  extension-element-prefixes="func"
  exclude-result-prefixes="my"
>
  <xsl:output method="xml" omit-xml-declaration="yes"/>

  <func:function name="my:ownfunc">
    <xsl:param name="data"/>
    <xsl:param name="suffix" select="'%'"/>
    <xsl:choose>
      <xsl:when test="string(number($data)) != 'NaN'">
        <func:result select="concat(format-number($data,'#0.00'),$suffix)"/>
      </xsl:when>
      <xsl:otherwise>
        <func:result select="$data"/>
      </xsl:otherwise>
    </xsl:choose>
  </func:function>

  <xsl:template match="/">
    <out>
      <xsl:for-each select="*/@*">
        <xsl:value-of select="my:ownfunc(.)"/>
        <xsl:text>
</xsl:text>
      </xsl:for-each>
    </out>
  </xsl:template>

</xsl:transform>

Sample run:

$ xsltproc --version | grep proc
xsltproc was compiled against libxml 20910, libxslt 10134 and libexslt 820
$
$ printf '%s\n' '<v v1="12.345" v2="2022w05" v3="-.75" v4="1e3"/>' | xsltproc file.xsl -
<out>12.35%
2022w05
-0.75%
1000.00%
</out>
  •  Tags:  
  • Related