XSL:有没有一种简单的方法可以防止寡妇?

2024-01-11

我本来希望打电话..

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

and

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

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

Lorem ipsum dolor sit amet, consectetur adipiscing#elit.

and

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

您所需要做的就是替换每个文本节点中的最后一个空格:

<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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

XSL:有没有一种简单的方法可以防止寡妇? 的相关文章

随机推荐