Thursday, December 28, 2023

Managing complexity of XPath 3.1 'if' expressions, in the context of XSLT 3.0

I've just been playing around, with the following XSLT transformation example, and thought of sharing this as a blog post here.

Let's consider following XSLT 3.0 stylesheet, that we'll use to transform an XML document mentioned thereafter,

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

                         xmlns:xs="http://www.w3.org/2001/XMLSchema"

                         xmlns:fn0="http://fn0"

                         exclude-result-prefixes="xs fn0"

                         version="3.0">

  <xsl:output method="xml" indent="yes"/>

  <xsl:variable name="date1" select="xs:date('2005-10-12')" as="xs:date"/>

  <xsl:template match="/root">

      <root>

          <xsl:copy-of select="if (fn0:func1($date1)) then a else b"/>

     </root>

  </xsl:template>

  <!-- An XSLT stylesheet function, that performs a specific boolean valued computation. The result of this function, is used to perform computations of distinct branches of XPath 'if' condition used within xsl:copy-of instruction written earlier above. -->

 <xsl:function name="fn0:func1" as="xs:boolean">

     <xsl:param name="date1" as="xs:date"/>

     <xsl:sequence select="if (current-date() lt $date1) 

                                                                               then true() 

                                                                               else false()"/>

   </xsl:function>

</xsl:stylesheet>

The corresponding XML instance document is following,

<?xml version="1.0" encoding="utf-8"?>

<root>

    <a/>

    <b/>

</root>

The two possible XSLT transformation results (depending upon the result of following XPath expression comparison : current-date() lt $date1, for the above mentioned XSLT transformation are following:

<?xml version="1.0" encoding="UTF-8"?><root>

  <b/>

</root>

and,

<?xml version="1.0" encoding="UTF-8"?><root>

  <a/>

</root>

Within the above mentioned XSLT transformation example, we may observe how, the XPath 3.1 'if' expressions have been written to achieve the desired XSLT transformation results. We're able to write stylesheet functions that may be significantly complex to produce boolean result, which may act as XPath 'if' expression branching condition.

I hope that, the above mentioned XSLT transformation example is useful.


No comments: