使用xalan扩展在XSL中使用Java集合

bsi*_*nau 3 java xml xslt collections xalan

我想迭代ArrayList <String>并将所有字符串放到输出树,但不知道如何做到这一点.

java方法:

public ArrayList<String> getErrorList(String name) {
    if (errorMap.containsKey(name)) {
        return errorMap.get(name);
    }
    return new ArrayList<>();
}
Run Code Online (Sandbox Code Playgroud)

xsl文件:

<xsl:variable name="list">
    <xsl:value-of select="validator:getErrorList($validator, 'model')"/>
</xsl:variable>

<tr>
    <td style="color: red;">
        <ul>
            <li> first string from ArrayList </li>
            . . .
            <li> last string from ArrayList </li>
        </ul>
    </td>
</tr>
Run Code Online (Sandbox Code Playgroud)

我对xsl很新,所以我向你寻求帮助.

小智 6

你的错误是初始化变量,如

<xsl:variable name="list">
    <xsl:value-of select="validator:getErrorList($validator, 'model')"/>
</xsl:variable>
Run Code Online (Sandbox Code Playgroud)

因为xslt认为,这个变量的值是#STRING,所以你会得到错误

对于扩展函数,找不到方法java.util.ArrayList.size([ExpressionContext,] #STRING).

您必须使用下一个声明,而不是之前的声明:

<xsl:variable name="list" select="validator:getErrorList($validator, 'model')"/>
Run Code Online (Sandbox Code Playgroud)

所以,方法getErrorList会返回ArrayList对象.下一代码将向您展示如何使用XSL功能迭代ArrayList集合:

<xsl:variable name="list" select="validator:getErrorList($validator, 'model')"/>
<xsl:variable name="length" select="list:size($list)"/>
<xsl:if test="$length > 0">
    <xsl:call-template name="looper">
        <xsl:with-param name="iterations" select="$length - 1"/>
        <xsl:with-param name="list" select="$list"/>
    </xsl:call-template>
</xsl:if>
. . .
<xsl:template name="looper">
    <xsl:param name="iterations"/>
    <xsl:param name="list"/>
    <xsl:if test="$iterations > -1">
        <xsl:value-of select="list:get($list, $iterations)"></xsl:value-of>
        <xsl:call-template name="looper">
             <xsl:with-param name="iterations" select="$iterations - 1"/>
               <xsl:with-param name="list" select="$list"/>
          </xsl:call-template>
     </xsl:if>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

所以,你必须使用递归,因为它不可能在函数式语言中使用循环,例如XSLT.你可以在这里阅读它