问题
I am having this below variable
<xsl:variable name="testvar">
d
e
d
</xsl:variable>
and I have this function:
<xsl:choose>
<xsl:when test="not($str-input)">
<func:result select="false()"/>
</xsl:when>
<xsl:otherwise>
<func:result select="translate($str-input,$new-line,'_')"/>
</xsl:otherwise>
</xsl:choose>
</func:function>
And when I tested the function I saw my result is like this: _ d _ e _ d_ and I want my result to be only
d _ e _ d
回答1:
In XSLT 1.0:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:variable name="new-line" select="' '" />
<xsl:variable name="str-input">
d
e
d
</xsl:variable>
<!-- your <xsl:choose>, slightly modified -->
<xsl:template match="/">
<xsl:choose>
<xsl:when test="not($str-input)">
<xsl:value-of select="false()"/>
</xsl:when>
<xsl:otherwise>
<xsl:variable name="temp">
<xsl:call-template name="normalize-newline">
<xsl:with-param name="str" select="$str-input" />
</xsl:call-template>
</xsl:variable>
<xsl:value-of select="translate($temp, $new-line, '_')" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- a template that trims leading and trailing newlines -->
<xsl:template name="normalize-newline">
<xsl:param name="str" select="''" />
<xsl:variable name="temp" select="concat($str, $new-line)" />
<xsl:variable name="head" select="substring-before($temp, $new-line)" />
<xsl:variable name="tail" select="substring-after($temp, $new-line)" />
<xsl:variable name="hasHead" select="translate(normalize-space($head), ' ', '') != ''" />
<xsl:variable name="hasTail" select="translate(normalize-space($tail), ' ', '') != ''" />
<xsl:if test="$hasHead">
<xsl:value-of select="$head" />
<xsl:if test="$hasTail">
<xsl:value-of select="$new-line" />
</xsl:if>
</xsl:if>
<xsl:if test="$hasTail">
<xsl:call-template name="normalize-newline">
<xsl:with-param name="str" select="$tail" />
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
returns:
" d _ e _ d"
The spaces are part the variable value. You could remove them using normalize-space()
, but since I don't know what "d"
or "e"
is in reality I leave them unchanged.
回答2:
Can you change your variable to:
<xsl:variable name="testvar">
d
e
d</xsl:variable>
?
来源:https://stackoverflow.com/questions/1492736/xslt-1-0-replace-new-line-character-with