XSLT:有条件地添加Modify Substring

时间:2011-01-12 18:55:40

标签: xml xslt docbook

我有一个添加零宽度字符的函数。但它并不像我想要的那样工作。如果它不包含正常空格,如何每15个字符 添加零空格字符?

<xsl:template match="text()[parent::d:entry]">
    <xsl:call-template name="intersperse-with-zero-spaces">
        <xsl:with-param name="str" select="."/>
        <xsl:with-param name="max_length" select="number(15)"/>
    </xsl:call-template>
</xsl:template>
<xsl:template name="intersperse-with-zero-spaces">
        <xsl:param name="str"/>
        <xsl:param name="max_length"/>
        <xsl:variable name="ret">
            <xsl:value-of select="substring($str, 1, $max_length)"/>
            <xsl:if test="string-length($str) &gt; $max_length">
                <xsl:value-of select="'&#x200b;'"/>
                <xsl:call-template name="intersperse-with-zero-spaces">
                    <xsl:with-param name="str" select="substring($str, $max_length + 1)"/>
                    <xsl:with-param name="max_length" select="$max_length"/>
                </xsl:call-template>
            </xsl:if>
        </xsl:variable>
        <xsl:value-of select="$ret"/>
    </xsl:template>

1 个答案:

答案 0 :(得分:3)

一些提示。首先:

<xsl:template match="d:entry/text()">

优于

<xsl:template match="text()[parent::d:entry]">

然后:

<xsl:template name="intersperse-with-zero-spaces">
  <xsl:param name="str"/>
  <xsl:param name="max_length"/>

  <!-- your variable "ret" is not necessary at all -->

  <xsl:variable name="head" select="substring($str, 1, $max_length)" />
  <xsl:variable name="tail" select="substring($str, $max_length + 1)" />

  <xsl:value-of select="$head"/>

  <!-- the empty string evaluates to false -->
  <xsl:if test="$tail">
    <!-- there's no space present when translate() returns the same string
         and the $tail does not begin with a space, either  -->
    <xsl:if test="
      string-length(translate($head, ' ', '')) = string-length($head)
      and not(substring($tail, 1, 1) = ' ')
    ">
      <xsl:text>&#x200b;</xsl:text>
    </xsl:if>
    <xsl:call-template name="intersperse-with-zero-spaces">
      <xsl:with-param name="str"        select="$tail"/>
      <xsl:with-param name="max_length" select="$max_length"/>
    </xsl:call-template>
  </xsl:if>
</xsl:template>

另外,我可能会调用变量$interval,而不是$max_length。但这纯粹是装饰性的。