删除冗余标记样式代码XSLT

时间:2012-10-11 13:05:53

标签: xml xslt xsl-fo apache-fop

我正在通过Apache-FOP项目将我的XML文档转换为PDF文档,到目前为止一切顺利。除了,我有以后不容易配置。我的代码片段是这样的,

<fo:table-cell>
    <fo:block margin-top="5pt" text-align="left"><xsl:value-of select="" /></fo:block>
</fo:table-cell>
<fo:table-cell>
    <fo:block margin-top="5pt" text-align="center"><xsl:value-of select="" /></fo:block>
</fo:table-cell>
<fo:table-cell>
    <fo:block margin-top="5pt" text-align="center"><xsl:value-of select="" /></fo:block>
</fo:table-cell>
<fo:table-cell>
    <fo:block margin-top="5pt" text-align="center"><xsl:value-of select="" /></fo:block>
</fo:table-cell>
<fo:table-cell>
    <fo:block margin-top="5pt" text-align="center"><xsl:value-of select="" /></fo:block>
</fo:table-cell>
<fo:table-cell>
     <fo:block margin-top="5pt" text-align="center"><xsl:value-of select="" /></fo:block>
</fo:table-cell>

正如您在上面的代码中看到的,我经常margin-top="5pt" text-align="center"。我试图找到一种方法,这样我只能写一次这个值,之后我可以改变一个变量然后影响每个人。


研究发现:

到目前为止我发现,我可以在XSLT中使用参数并定义变量。以后,我可以使用,参数值可以是5pt。然后我就这样使用它。

<xsl:attribute name="margin-top">$var</xsl:attribute>

但这不是一个好的解决方案,因为它使我的代码完全不可读(不完全,但你知道我的意思)。在XSLT中有类似CSS的东西吗?

1 个答案:

答案 0 :(得分:4)

使用 xsl:attribute 可能是一种冗长的方式。最好在这里使用“属性值模板”,它允许您在线指定代码

<fo:block margin-top="{$var}" text-align="{$var2}">

花括号表示该值是要计算的表达式,而不是字面输出。

继续这一点,我认为 xsl:attribute-set 可能是你的朋友。这将允许您创建一组可以在以后应用于任何元素的属性。首先,您将定义属性集,如下所示:(注意,这应该在 xsl:stylesheet 元素下)

<xsl:attribute-set name="block">
  <xsl:attribute name="margin-top">5pt</xsl:attribute>
  <xsl:attribute name="text-align">left</xsl:attribute>
</xsl:attribute-set> 

然后,要使用它,您只需使用 xsl:use-attribute-sets 属性

<fo:block xsl:use-attribute-sets="block">

这应该输出以下内容:

<fo:block margin-top="5pt" text-align="left">

此外,如果您希望设置调用程序的值,您仍然可以“参数化”您的属性集。例如,以下内容也应该起作用

<xsl:param name="margin-top" select="'6pt'" />
<xsl:param name="text-align" select="'left'" />

<xsl:attribute-set name="block">
  <xsl:attribute name="margin-top"><xsl:value-of select="$margin-top" /></xsl:attribute>
  <xsl:attribute name="text-align"><xsl:value-of select="$text-align" /></xsl:attribute>
</xsl:attribute-set>