简体   繁体   中英

How to cut a dynamic string in xslt 1.0

I have a variable with this structure: var=A--B--C--D (which can be contains more or less separator "--". Like it can be var=A--B--C--D--E--F--G.. etc).

How can I easily convert this variable var into several variables dynamically in xsl such as: VAR1 = A; VARnew2 = B; VARnew3 = C; VARnew4 = D;

I have seen function like "substring-before" and i feel like I need to use a recursive template but i dont manage to understand how i can do it... Or maybe there is a better function than "substring-before" which will do it for me..?

Anyone able to help me? It will be very appreciated! Thank you

Because you can only use XSLT-1.0, a recursive attempt is the way to go:

This is a sample XML:

<?xml version="1.0" ?>
<root>
    <exampleString>A--B--C--D</exampleString>
    <exampleString>   --A--B--C--D</exampleString>
    <exampleString>A--B--C   --D--E--F--G</exampleString>    
    <exampleString>A--B--C--D--E--     </exampleString>
</root>

And this is a possible XSLT-1.0 solution:

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

    <xsl:template match="/root/exampleString">
      <xsl:call-template name="delimit">
        <xsl:with-param name="str" select="." />
      </xsl:call-template>
    </xsl:template>

    <xsl:template name="delimit">
        <xsl:param name="str" />
        <xsl:choose>
            <xsl:when test="substring-before($str,'--')">
                <xsl:if test="normalize-space(substring-before($str,'--'))">
                    <var><xsl:value-of select="normalize-space(substring-before($str,'--'))" /></var>
                </xsl:if>
                <xsl:call-template name="delimit">
                    <xsl:with-param name="str" select="substring-after($str,'--')" />
                </xsl:call-template>
            </xsl:when>
            <xsl:otherwise>
                <xsl:if test="normalize-space($str)">
                    <var><xsl:value-of select="$str" /></var>
                </xsl:if>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
    
</xsl:stylesheet>

Its output is

<var>A</var><var>B</var><var>C</var><var>D</var>
<var>A</var><var>B</var><var>C</var><var>D</var>
<var>A</var><var>B</var><var>C</var><var>D</var><var>E</var><var>F</var><var>G</var>    
<var>A</var><var>B</var><var>C</var><var>D</var><var>E</var>

Of course you can separate the <var> elements with newlines if you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM