首页 > 解决方案 > 使用 XSLT 1.0 的数组

问题描述

我在下面有一个简单的数组

<xsl:template match="/">
    <xsl:variable name="array">
        <Item>One</Item>
        <Item>Two</Item>
        <Item>Three</Item>
    </xsl:variable>
    <html>
        <body>
            <xsl:value-of select="$array"/>
        </body>
    </html>
</xsl:template> 

哪个显示

OneTwoThree

但是,当我尝试

<xsl:value-of select="$array[0]"/>

整个页面中断

知道如何访问数组中的“One”吗?

标签: arraysxmlxsltxslt-1.0

解决方案


首先,XSLT 1.0 中没有数组。您的变量是具有 3个子元素的结果树片段。Item

结果树片段不能直接解析;您需要首先使用处理器支持的扩展功能将它们转换为节点集 - 例如:

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

<xsl:template match="/">
    <xsl:variable name="array">
        <Item>One</Item>
        <Item>Two</Item>
        <Item>Three</Item>
    </xsl:variable>
    <html>
        <body>
            <xsl:value-of select="exsl:node-set($array)/Item[1]"/>
        </body>
    </html>
</xsl:template> 

</xsl:stylesheet>

或者,您可以通过直接解析样式表来绕过限制:

<xsl:template match="/">
    <xsl:variable name="array">
        <Item>One</Item>
        <Item>Two</Item>
        <Item>Three</Item>
    </xsl:variable>
    <html>
        <body>
            <xsl:value-of select="document('')//xsl:variable[@name='array']/Item[1]"/>
        </body>
    </html>
</xsl:template> 

请注意,节点编号从 1 开始,而不是 0。


推荐阅读