Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

string - Does xslt have split() function?

How do you split a string based on some separator?

Given a string Topic1,Topic2,Topic3, I want to split the string based on , to generate:

Topic1 Topic2 Topic3
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In XSLT 1.0 you have to built a recursive template. This stylesheet:

<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="','"/>
        <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>

Input:

<root>
<text>Item1, Item2, Item3</text>
</root>

Output:

<root>
    <text>
        <item>Item1</item>
        <item>Item2</item>
        <item>Item3</item>
    </text>
</root>

In XSLT 2.0 you have the tokenize() core function. So, this stylesheet:

<xsl:stylesheet version="2.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="separator" select="','"/>
        <xsl:for-each select="tokenize(.,$separator)">
                <item>
                    <xsl:value-of select="normalize-space(.)"/>
                </item>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

Result:

<root>
    <text>
        <item>Item1</item>
        <item>Item2</item>
        <item>Item3</item>
    </text>
</root>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...