XSLT连接两个数组

时间:2015-06-04 12:01:22

标签: arrays function xslt

我尝试以特殊方式连接两个字符串数组。数组看起来像这样:

  • 第一个数组(arg1):' A',' B',' C'
  • 第二个数组(arg2):' -3','',' -4'

结果应该是一个字符串:' A-3 / B / C-4'

但是使用我的代码,我得到的结果是这样的(只返回最后一部分):' C-4'

代码:

<xsl:function name="functx:k" as="xs:string">
    <xsl:param name="arg1" as="xs:string*"/>
    <xsl:param name="arg2" as="xs:string*"/>
    <xsl:variable name="indexedPath"/>
    <xsl:for-each select="$arg1">
        <xsl:variable name="i" select="position()" as="xs:integer"/>
        <xsl:variable name="indexedPathNew" select="concat($indexedPath, $arg1[$i], $arg2[$i], '/')"/>
        <xsl:variable name="indexedPath" select="$indexedPathNew"/>
        <xsl:choose>
            <xsl:when test="$i=count($arg1)">
                <xsl:value-of select="$indexedPathNew"/>
            </xsl:when>
        </xsl:choose>
    </xsl:for-each>      
</xsl:function>

第二种可能性是连接这两个字符串:

  • 第一个字符串:&#39; A / B / C&#39;
  • 第二个字符串:&#39; -3 // - 4&#39;

结果应该是(一个字符串):&#39; A-3 / B / C-4&#39;。我认为分裂然后连接更容易(我没有任何代码,这只是一个想法)。

你能帮助我找出我做错了什么,或者如何正确地做到这一点?

1 个答案:

答案 0 :(得分:4)

我想你只想要

<xsl:function name="functx:k" as="xs:string">
    <xsl:param name="arg1" as="xs:string*"/>
    <xsl:param name="arg2" as="xs:string*"/>
    <xsl:sequence select="string-join(for $pos in 1 to count($arg1)
return concat($arg1[$pos], $arg2[$pos]), '/')"/>
</xsl:function>

假设XSLT / XPath 3.0(例如Saxon 9.6已经提供),您可以将代码简化为

<xsl:function name="functx:k" as="xs:string">
    <xsl:param name="arg1" as="xs:string*"/>
    <xsl:param name="arg2" as="xs:string*"/>
    <xsl:sequence select="string-join(for-each-pair($arg1, $arg2, concat#2), '/')"/>
</xsl:function>

请注意,您的参数是字符串序列,而不是数组。您可能会在3.1版中使用数组作为语言的一部分:http://www.w3.org/TR/xpath-31/#id-arrays