2009-09-29 59 views
3

我有這個低於可變XSLT 1.0:替換爲新行字符_

<xsl:variable name="testvar"> 
     d 
     e 
     d 
    </xsl:variable> 

,我有這樣的功能:

<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> 

當我測試我看到的功能我結果是這樣的:_ d _ e _ d_ 並且我希望我的結果僅爲

d _ _êd

回答

3

在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> 

回報:

"  d _  e _  d" 

的空間是部分的可變值。您可以使用normalize-space()將它們刪除,但由於我不知道"d""e"實際上是什麼,所以我將它們保持不變。

+0

@Tomalak 我有一個問題。你只有變量: 如何回車「\ r」。 我不確定在ded後是否有回車(\ r) d \ r \ n或d \ n \ r e \ r \ n或e \ n \ r d \ r \ n或d \ n \ r 2009-09-29 15:03:23

+0

更改''期待在你的價值中出現。例如,'select ='' '''也可以。 – Tomalak 2009-09-29 15:11:40

+0

或者,你可以使用'translate($ str,' ','')''去除任何出現' '的東西 - 無論你認爲合適的措施。 – Tomalak 2009-09-29 15:13:52

0

你可以改變你變量:

<xsl:variable name="testvar"> 
     d 
     e 
     d</xsl:variable> 

+0

我可以改變它,但功能不夠靈活。變量的內容也會從一個沒有預分配的XML文件中讀取。 – 2009-09-29 14:13:47