XSLT拆分字符串以创建选择选项

时间:2016-07-04 03:50:04

标签: html xslt xslt-1.0

我试图在XSLT中创建一个下拉元素,其中值和标签由冒号(:)和下一个项的换行符分隔。

第一,我有一个简单的xml像; (系统生成)

-((uint)2147483648)
然后我把它分成了:

<root>
<item>
test1 : Test 1
test2 : Test 2
test3 : Test 3
</item>
</root>

输出:

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

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>


    <xsl:template match="text/text()" name="tokenize">

        <xsl:param name="text" select="."/>
        <xsl:param name="separator" select="'&#x0a;'"/>

        <xsl:choose>
            <xsl:when test="not(contains($text, $separator))">
                <item><xsl:value-of select="normalize-space($text)"/></item>
            </xsl:when>
            <xsl:otherwise>
                <item>
                    <xsl:value-of select="normalize-space(substring-before($text, $separator))"/>
                </item>

                <xsl:call-template name="tokenize">
                    <xsl:with-param name="text" select="substring-after($text, $separator)"/>
                </xsl:call-template>

            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

然后我不知道下一步是什么?是否可以创建第二个模板来创建html选择?

<root>
<text>
<item>test1 : Test 1</item>
<item>test2 : Test 2</item>
<item>test3 : Test 3</item>
</text>
</root>

请helppppp ....:&#39;(

1 个答案:

答案 0 :(得分:1)

好吧,如果你将样式表更改为:

XSLT 1.0

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

<xsl:template match="/root">
    <html>
        <body>
            <xsl:apply-templates/>
        </body>
    </html>
</xsl:template>

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

<xsl:template name="tokenize">
    <xsl:param name="text"/>
    <xsl:param name="delimiter" select="'&#10;'"/>
        <xsl:variable name="token" select="substring-before(concat($text, $delimiter), $delimiter)" />
        <xsl:if test="$token">
            <option value="{substring-before($token, ' : ')}">
                <xsl:value-of select="substring-after($token, ' : ')"/>
            </option>
        </xsl:if>
        <xsl:if test="contains($text, $delimiter)">
            <!-- recursive call -->
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="substring-after($text, $delimiter)"/>
            </xsl:call-template>
        </xsl:if>
</xsl:template>

</xsl:stylesheet>

您将收到:

<html>
   <body>
      <select>
         <option value="test1">Test 1</option>
         <option value="test2">Test 2</option>
         <option value="test3">Test 3</option>
      </select>
   </body>
</html>