XSL:for循环中的标记化问题

时间:2011-12-01 13:11:31

标签: xslt tokenize

我使用以下样式表在excel工作簿中显示包含数据的表。我无法获得所需的结果,而是显示与下面给出的不同。

建议请?

使用的样式表:

<xsl:stylesheet>
<xsl:template match="/">
    <xsl:variable name="test1" select="str:tokenize('1$,$2$,$3$,$4$,$5','$,$')" />
    <xsl:variable name="test2" select="str:tokenize('a$,$b$,$c$,$d$,$e','$,$')" />
    <xsl:for-each select="str:split('1a$,$2b$,$3c$,$4d$,$5e','$,$')>
        <row>
            <cell Index="1">
                <xsl:value-of select="$test1[position()]" />
            </cell>
            <cell Index="2">
                <xsl:value-of select="$test2[position()]" />
            </cell>
        </row>
    </xsl:for-each>
</xsl:template>

预期结果:

1 a

2 b

3 c

4 d

5 e

结果显示为

a b

c d

ë

它似乎正在显示最新的tokenize值。 如何获得尊重的价值观。

1 个答案:

答案 0 :(得分:2)

好问题,+ 1。

在我看来,而不是

<xsl:value-of select="$test1[position()]" />

必须

<xsl:value-of select="$test1[position() = current()]" />

对于第二个 <xsl:value-of>

,完全相同的观察结果

<强>解释

任何表达

 $var[position()]

相当于:

$var

因为position()只能包含值&gt; = 1而[position()]表示 position()的布尔值,以及任何非负值的布尔值根据定义,数字为true()

如果我们想在节点集$ var中选择第k个节点,在XPath 1.0中,它是弱类型的并且不知道$k包含整数,我们必须写:

$var[position() = $k]

这是一个完整的,相应的XSLT 2.0解决方案

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>

    <xsl:template match="/">
        <xsl:variable name="test1" select=
        "tokenize('1$,$2$,$3$,$4$,$5','\$,\$')" />

        <xsl:variable name="test2" select=
        "tokenize('a$,$b$,$c$,$d$,$e','\$,\$')" />

        <xsl:for-each select="tokenize('1a$,$2b$,$3c$,$4d$,$5e','\$,\$')">
            <row>
                <cell Index="1">
                    <xsl:value-of select="$test1[position()]" />
                </cell>
                <cell Index="2">
                    <xsl:value-of select="$test2[position()]" />
                </cell>
            </row>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

应用于任何XML文档(忽略)时,会生成所需的正确结果

<row xmlns:xs="http://www.w3.org/2001/XMLSchema">
   <cell Index="1">1 2 3 4 5</cell>
   <cell Index="2">a b c d e</cell>
</row>
<row xmlns:xs="http://www.w3.org/2001/XMLSchema">
   <cell Index="1">1 2 3 4 5</cell>
   <cell Index="2">a b c d e</cell>
</row>
<row xmlns:xs="http://www.w3.org/2001/XMLSchema">
   <cell Index="1">1 2 3 4 5</cell>
   <cell Index="2">a b c d e</cell>
</row>
<row xmlns:xs="http://www.w3.org/2001/XMLSchema">
   <cell Index="1">1 2 3 4 5</cell>
   <cell Index="2">a b c d e</cell>
</row>
<row xmlns:xs="http://www.w3.org/2001/XMLSchema">
   <cell Index="1">1 2 3 4 5</cell>
   <cell Index="2">a b c d e</cell>
</row>