尝试插入空行时在XSLT中测试文本内容

时间:2011-04-13 14:46:33

标签: html xslt xsl-fo

前段时间我问过这个问题:using xslt stylesheet to convert xhtml blank lines to an XSL-FO blank line

但是,我现在有一个类似的问题,那里建议的修复不起作用。

之前的解决方案看起来像这样:

  <xsl:template match="html:br[following-sibling::*[1][self::html:br]]">
    <fo:block space-after="1em">
      <xsl:call-template name="process-common-attributes"/>
    </fo:block>
  </xsl:template>

 <xsl:template match="html:br[preceding-sibling::*[1][self::html:br]]" />

  <xsl:template match="html:br">
    <fo:block>
      <xsl:call-template name="process-common-attributes"/>
    </fo:block>
  </xsl:template>

但我现在有一段看起来像这样的HTML:

<p>text<br />text<br />text<br /><br /><br />text</p>

与上一篇文章的不同之处在于,这里我没有文本元素(如span),而只是简单地交替文本和br元素。在我的例子中,这将错误地给出所有br的正面。不幸的是,我无法控制输入HTML。

我能想出的理想解决方案是只在下一个br和这个之间没有文本时插入具有1em高度的fo:block。有没有人知道如何实现这个或更好的解决这个问题的方法(我不想用\ n替换所有br标签并设置linefeed-treatment以保留,因为这将打开一整套新的蠕虫)

编辑:所需的输出是:

text
text
text


text

所以它应该保留(多个)换行符,但不能在单<br>之后添加额外的白行。

这在XSL-FO中的表现如何(带有前后空格的初始块和空格 - 来自&lt; p&gt;元素的转换)

                <fo:block space-after="1em" space-before="1em">text
                  <fo:block/>text
                  <fo:block/>text
                  <fo:block space-after="1em"/>
                  <fo:block space-after="1em"/>
                  <fo:block/>text
                </fo:block>

我愿意接受建议。

1 个答案:

答案 0 :(得分:2)

此样式表:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <xsl:template match="p">
        <fo:block space-after="1em" space-before="1em">
            <xsl:apply-templates/>
        </fo:block>
    </xsl:template>
    <xsl:template match="br[following-sibling::node()[1]/self::br]">
        <fo:block space-after="1em"/>
    </xsl:template>
    <xsl:template match="br">
        <fo:block/>
    </xsl:template>
</xsl:stylesheet>

输出:

<fo:block space-after="1em" space-before="1em"
 xmlns:fo="http://www.w3.org/1999/XSL/Format">text
    <fo:block />text
    <fo:block />text
    <fo:block space-after="1em" />
    <fo:block space-after="1em" />
    <fo:block />text
</fo:block>