Home > Enterprise >  XSLT 2.0: Apply a transformation to an array of strings
XSLT 2.0: Apply a transformation to an array of strings

Time:09-06

Would appreciate some help in the below problem.

For the below xml:

<test>
<a>1232</a>
<a>1236</a>
<a>1239</a>     
</test>

My goal is to return the first element only if all elements have the same value without taking the last character into account. Otherwise I want to throw some exception or return some hardcoded value. The example above should return 1232.

The example below should throw error because 123,113,123 ( values without last char) are not all equal. :

<test>
<a>1232</a>
<a>1136</a>
<a>1239</a>     
</test>

What I have tried so far:

I know that I can get all elements as a collection of string by using

<xsl:variable name="all_As" select="/test/a"/>

I also know that I can loop through all_As and perform the transformation.

<xsl:for-each select="$all_As">
 <xsl:value-of select="substring(current(), 1, string-length(current())-1))"/>
 </xsl:for-each>

But what is not clear to me is how do I perform the operation while keeping the array in memory? Ideally I would want to have a variable $all_transformed_As which would hold the transformed version of the original array? Is this possible to do in xslt? Is there some easier way to perform what I want to do?

CodePudding user response:

Try something along the lines of:

XSLT 2.0

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/test">
    <result>
        <xsl:choose>
            <xsl:when test="count(distinct-values(a/substring(., 1, string-length(.) - 1))) > 1">error</xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="a[1]" />
            </xsl:otherwise>
        </xsl:choose>
    </result>
</xsl:template>

</xsl:stylesheet>

Note that this could be a bit simpler if the length of the strings is known in advance.

  • Related