【问题标题】:XSL or XSLT or XSLFO: which can expand text?XSL 或 XSLT 和 XSL FO:哪个可以扩展文本?
【发布时间】:2011-09-01 22:31:47
【问题描述】:

假设我有一个 XML 文件:

<document>
  <title>How the West was Won</title>
  <chapter>
    Lorem Ipsum Blah .....
  </chapter>
</document>

是否可以使用 XSLT 或 XSLFO 或 XSL 来呈现这样的标题:

How the West was Won
--------------------

Lorem Ipsum Blah .....

如何在标题后面的行上生成正确数量的破折号?

【问题讨论】:

  • 用什么渲染? PDF (XSL-FO)?文本 (XSL-T)? XHTML/HTML (XSL-T)?
  • 对不起,我应该说..纯文本。我所追求的是获取 rst2html 的 xml 输出并制作一个格式化的文本文件。

标签: xslt


【解决方案1】:

我知道这很不典型,但你也可以使用模板模式:

    <xsl:template match="title">
        <xsl:variable name="dashes">
            <xsl:apply-templates select="." mode="dashes"/>
        </xsl:variable>
        <xsl:value-of select="concat(.,'&#10;',$dashes,'&#10;')"/>
    </xsl:template>

    <xsl:template match="text()" mode="dashes">
        <xsl:param name="length" select="string-length() - 1"/>
        <xsl:text>-</xsl:text>
        <xsl:apply-templates select="self::text()[boolean($length)]" 
            mode="dashes">
            <xsl:with-param name="length" select="$length - 1"/>
        </xsl:apply-templates>
    </xsl:template>

【讨论】:

  • 我将输出方法设置为文本(尽管我确实从文件顶部排除了 xml 声明)。模板如何生成破折号?
【解决方案2】:

试试这个:

  <xsl:template match="title">
  <xsl:value-of select="text()"/>
  <xsl:text>
  </xsl:text>
  <xsl:call-template name="Underline">
    <xsl:with-param name="length" select="string-length(text())"/>
  </xsl:call-template>
  </xsl:template>

  <xsl:template name="Underline">
    <xsl:param name="length"/>
    <xsl:choose>
      <xsl:when test="$length > 0">-<xsl:call-template name="Underline"><xsl:with-param name="length" select="$length - 1"/></xsl:call-template></xsl:when>
    </xsl:choose>    
  </xsl:template>

Underline 是一个递归模板,输出给定数量的破折号。

【讨论】:

  • 谢谢,这正是我所需要的。
【解决方案3】:

这是在 XSLT 2.0 中更简单的另一种情况。

<xsl:for-each select="1 to string-length(title)">-</xsl:for-each>

【讨论】:

  • 这样更干净。我希望创建一个返回“=”“-”或“~”的函数,具体取决于 标签嵌套在其他标题中的深度。
猜你喜欢
  • 2017-08-13
  • 2012-03-15
  • 1970-01-01
  • 2010-10-18
  • 1970-01-01
  • 2011-05-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
相关资源
最近更新 更多