如何在xslt中生成字母列表

时间:2016-09-13 02:49:39

标签: xml xslt xslt-1.0

如何使用xslt中的链接创建alphatical列表,例如;

<a href="sample.htm?letter=A">A</a>
<a href="sample.htm?letter=B">B</a>
<a href="sample.htm?letter=C">C</a>
...up to..
<a href="sample.htm?letter=Z">Z</a>

它可以是xml然后转换

<node>
    <letter>ABCDEFGHIJKLMNOPQRSTUVWXYZ</text>
</node>

还是只是变种?

<xsl:variable name="letter">ABCDEFGHIJKLMNOPQRSTUVWXYZ</xsl:variable>

2 个答案:

答案 0 :(得分:1)

XSLT 1.0

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

    <xsl:output method="html"/>

    <xsl:variable name="url">sample.htm</xsl:variable>
    <xsl:variable name="letter">ABCDEFGHIJKLMNOPQRSTUVWXYZ</xsl:variable>

    <xsl:template match="/">
        <xsl:call-template name="iterate">
            <xsl:with-param name="string" select="$letter"/>
        </xsl:call-template>
    </xsl:template>

    <xsl:template name="iterate">
        <xsl:param name="string"/>
        <xsl:param name="length" select="1" />

        <xsl:if test="string-length($string)">

            <xsl:variable name="char" select="substring($string, 1, 1)" />

            <xsl:call-template name="createEntry">
                <xsl:with-param name="token" select="$char"/>
            </xsl:call-template>

            <xsl:call-template name="iterate">
                <xsl:with-param name="string" select="substring-after($string, $char)" />
            </xsl:call-template>
        </xsl:if>        
    </xsl:template>

    <xsl:template name="createEntry">
        <xsl:param name="token"/>
        <a href="{$url}?letter={$token}"><xsl:value-of select="$token"/></a><br/>
    </xsl:template>

</xsl:stylesheet>

<强>解释

将字母存储到您建议的变量中。

将整个字符串作为参数iterate传递给函数string。 [可选参数:length]

将单个字符传递给函数createEntry

函数createEntry执行输出。

如果你愿意,可以试一试

答案 1 :(得分:0)

经过大量测试。终于我明白了!对于那些需要它以供将来参考的人。这是我的代码。

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>

<xsl:variable name="url">sample.htm</xsl:variable>
<xsl:template match="node">
    <xsl:apply-templates/>
</xsl:template>

<xsl:template match="letter">
    <xsl:call-template name="element"><xsl:with-param name="text" select="."/></xsl:call-template>
</xsl:template>

<xsl:template name="element">
    <xsl:param name="text"/>

    <xsl:variable name="token" select="substring($text, 1, 1)" />

    <xsl:if test="$token">
        <a href="{$url}?letter={$token}"><xsl:value-of select="$token"/></a><br/>
    </xsl:if>

    <xsl:if test="string-length($text) > 1">
        <xsl:call-template name="element">
            <xsl:with-param name="text" select="substring($text, 2, string-length($text) - 1)"/>
        </xsl:call-template>
    </xsl:if>

</xsl:template>

</xsl:stylesheet>

如果您有更好或更简单的解决方案,请发表评论。

相关问题