【问题标题】:How do I match the elements generated by xsl-fo?如何匹配 xsl-fo 生成的元素?
【发布时间】:2018-02-23 11:53:03
【问题描述】:

我有一个像这样的.xsl 文件:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:exslt="http://exslt.org/common">
  <xsl:template match="/>
    <fo:root>
      <fo:block>...</fo:block>
    </fo:root>
  </xsl:template>
</xsl:stylesheet>

如何使用模板匹配生成的fo 元素并为其设置样式?例如,如果我想给我的fo:table-cells 提供红色背景,我希望能够做到

<xsl:template match="fo:table-cell">
  <xsl:attribute name="background-color">red</xsl:attribute>
</xsl:template>

我找到了this,然后尝试了类似

  <xsl:template match="/>
    <xsl:variable name="foRoot">
      <fo:root>
        <fo:block>...</fo:block>
      </fo:root>
    </xsl:variable>
    <xsl:apply-templates select="exslt:node-set($foRoot)" />
  </xsl:template>

但是由于无限递归,这会导致堆栈溢出。当我试图避免这种情况时,例如通过做

<xsl:apply-templates select="exslt:node-set($foRoot)/*" />

我得到一个空文件。当试图通过添加来修复那个

<xsl:copy-of select="$foRoot" />

之后,我没有收到任何错误,但表格单元格仍然具有默认的白色背景。

【问题讨论】:

    标签: xslt xslt-2.0 xsl-fo


    【解决方案1】:

    如果您真的使用 XSLT 2 处理器,那么首先您不需要exsl:node-set

    至于你的模板

    <xsl:template match="fo:table-cell">
      <xsl:attribute name="background-color">red</xsl:attribute>
    </xsl:template>
    

    这将匹配 FO table-cell 但将其转换为属性。所以你宁愿想要

    <xsl:template match="fo:table-cell">
      <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:attribute name="background-color">red</xsl:attribute>
        <xsl:apply-templates/>
      </xsl:copy>
    </xsl:template>
    

    因为这会将属性添加到元素的浅表副本中,然后继续处理具有apply-templates 的子元素。

    当然你还需要添加身份转换模板

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

    确保复制您不想更改的元素。如果您拥有的其他模板干扰身份转换,则可能需要使用模式来分隔处理步骤。

    【讨论】:

    • 谢谢!这就像一种魅力(即使它最终会变得冗长......)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 2017-06-19
    相关资源
    最近更新 更多