XSLT 1.0: replace new line character with _

ⅰ亾dé卋堺 提交于 2019-12-10 20:00:57

问题


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="'&#10;'" />

  <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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!