如何匹配 xsl-fo 生成的元素?

How do I match the elements generated by xsl-fo?

我有一个这样的 .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-cell 一个红色背景,我希望能够做到

<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)/*" />

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

来修复 that
<xsl:copy-of select="$foRoot" />

紧接着,我没有收到任何错误,但 table 单元格仍然具有默认的白色背景。

如果您真的使用 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>

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