XSL:有没有一种简单的方法来预防寡妇? [英] XSL: Is there an easy way to prevent widows?

查看:102
本文介绍了XSL:有没有一种简单的方法来预防寡妇?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望打电话给..

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

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

And then it would look for the last space in the text and replace it with #160; when finalized.

应该能够支持

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

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

请使用其他字符,例如#来回答/证明,所以我测试的结果将是

Please use a different character, like # to answer/prove, so the result when I test would be

Lorem ipsum dolor sit amet, consectetur adipiscing#elit.

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

推荐答案

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

All that you need is to replace the last space in every text node:

<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"可以处理文本节点和保留封闭标记的段落.

The mode="widow-fix" can process both text nodes and paragraphs preserving the enclosing tag.

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

I used such document as a test source

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

将转换为以下内容

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

这篇关于XSL:有没有一种简单的方法来预防寡妇?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆