3

我希望打电话..

<xsl:call-template name="widow-fix">
  <with-param name="text" select="text"></with-param>
</xsl:call-template>

然后它会space在文本中查找最后一个并在完成时将其替换为#160;


应该可以支持

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

请使用不同的字符,例如#回答/证明,所以我测试时的结果是

Lorem ipsum dolor sit amet, consectetur adipiscing#elit.

<p>Lorem ipsum dolor sit amet, consectetur adipiscing#elit.</p>
4

2 回答 2

4

您只需要替换每个文本节点中的最后一个空格:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">


<xsl:template match="p | text()">
    <xsl:apply-templates select="." mode="widow-fix"/>
</xsl:template>


<xsl:template match="* | @*">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>


<xsl:template match="* | @*" mode="widow-fix">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()" mode="widow-fix"/>
    </xsl:copy>
</xsl:template>


<xsl:template match="text()[contains(., ' ')]" mode="widow-fix">
    <xsl:call-template name="text">
        <xsl:with-param name="text" select="."/>
    </xsl:call-template>
</xsl:template>


<xsl:template name="text">
    <xsl:param name="text"/>

    <xsl:variable name="substring-before" select="substring-before($text, ' ')"/>
    <xsl:variable name="substring-after"  select="substring-after($text, ' ')"/>

    <xsl:choose>
        <xsl:when test="contains($substring-after, ' ')">
            <xsl:value-of select="$substring-before"/>
            <xsl:text> </xsl:text>

            <xsl:call-template name="text">
                <xsl:with-param name="text" select="$substring-after"/>
            </xsl:call-template>
        </xsl:when>

        <xsl:otherwise>
            <xsl:value-of select="$substring-before"/>
            <!--<xsl:text>&#160;</xsl:text>-->
            <xsl:text>#</xsl:text>
            <xsl:value-of select="$substring-after"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>


</xsl:stylesheet>

mode="widow-fix" 可以处理文本节点和保留封闭标签的段落。

我用这样的文件作为测试源

<book>
<p>Highly random content</p>
in this book
</book>

转换为以下

<book>
<p>Highly random#content</p>
in this#book
</book>
于 2013-11-05T16:43:13.807 回答
0

您需要“select=text()”,并且可以使用 xs: 字符串函数之一进行替换,但我不会将结果描述为防止寡妇。

于 2013-10-30T22:22:29.983 回答