2009-09-29 111 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