使用xsl:apply-template和xsl:call-template时,是否可以根据XML代码按顺序生成pdf?

时间:2019-04-01 18:57:50

标签: java xml xslt

我目前正在使用XML代码和XSLT用Java生成多页PDF文档。

XML是按照与输入相同的顺序生成的(这正是我想要的)。

但是,在生成PDF时遇到了组织问题。

由于使用调用模板和应用模板调用了多个样式表,因此它将按照我的应用模板类别的顺序生成PDF。

为简化说明,下面是一个简化示例:

Input:            
cheese
milk
bread
bagels
rice
eggs

鉴于此输入,我生成了与订单匹配的XML。

<food>
      <dairy>
          <cheese>
                   <.....></>   <---------cheese information
                   <.....></>    <---------etc.
          </cheese>
     </dairy>



      <grains>
          <bread>
                   <.....></>    <---------bread information
                   <.....></>    <---------etc.
          </bread>
     </grains>
 </food>

然后,样式表使用XML代码通过以下方式生成PDF

<xsl:apply-templates select="/food/dairy"/>
<xsl:apply-templates select="/food/grains"/>

<xsl:template match="/food/dairy">
      <xsl:call-template name="dairy"></xsl:call-template>
</xsl:template>
<xsl:template match="/food/grains">
      <xsl:call-template name="grains"></xsl:call-template>
</xsl:template>

现在发生的是,我们使鸡蛋跳了起来,跟随奶酪和牛奶,而不是保持顺序不变。

调用和应用模板时是否可以保持XML顺序?

我只能找到以下相关信息:Apply XSLT template respecting the order in the XML-source

虽然与我的问题不太匹配。

1 个答案:

答案 0 :(得分:0)

我发现您的问题令人困惑。在您的示例中,匹配模板dairy之前先应用匹配grains的模板。为了防止这种情况并保持文档顺序,您应该替换:

<xsl:apply-templates select="/food/dairy"/>
<xsl:apply-templates select="/food/grains"/>

具有:

<xsl:apply-templates select="/food/dairy | /food/grains"/>

当然,这是一个完全伪造的示例-仅因为XML文档不能包含两个根元素。