包括XSL模板和合并输出

时间:2017-04-12 10:17:03

标签: xml xslt

我有2个xsl样式表,它们都转换元素<Group id="all">

输出应该合并,而是被main.xsltinclude.xslt覆盖。 (取决于订单)

我不想修改include.xslt文件,因为它在其他样式表中共享,不应修改。

main.xslt

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:include href="include.xslt"/>
  <xsl:template match="Group[@id='all']">
    <xsl:copy>
      <xsl:copy-of select="@*|node()" />
      <xsl:apply-templates select="document('part1.xml')" />
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

include.xslt

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="Group[@id='all']">
    <xsl:copy>
      <xsl:copy-of select="@*|node()" />
      <xsl:apply-templates select="document('part2.xml')" />
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

input.xml中

<?xml version="1.0"?>

<Group id="all">
testdata below:
</Group>

part1.xml

<?xml version="1.0"?>
<data id="test1">
Here is some test data.
</data>

part2.xml

<?xml version="1.0"?>
<data id="test2">
Here is some more data.
</data>

实际输出:

<?xml version="1.0"?>
<Group id="all">
testdata below:

Here is some test data.
</Group>

预期产出:

<?xml version="1.0"?>
<Group id="all">
testdata below:

Here is some test data.
Here is some more data.
</Group>

1 个答案:

答案 0 :(得分:0)

执行此操作的常规方法是使用xsl:import代替xsl:include,然后添加xsl:apply-imports ...

<强> main.xslt

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:import href="include.xslt"/>
  <xsl:template match="Group[@id='all']">
    <xsl:copy>
      <xsl:copy-of select="@*|node()" />
      <xsl:apply-templates select="document('part1.xml')" />
      <xsl:apply-imports/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

但是,你最终得到的是两个Group个元素,一个嵌套在另一个元素内(你可以在xsl:apply-imports之后移动xsl:copy以获得一个元素另一个)......

<Group id="all">
testdata below:

Here is some test data.
<Group id="all">
testdata below:

Here is some more data.
</Group></Group>

所以我可以看到你要么(选择一个):

  • 第二次处理输出以实际合并两个Group元素。
  • 使用node-set()之类的扩展函数(或使用XSLT 2.0)将Group结构保存在变量中,然后处理变量以合并Group s。
  • 修改include.xslt,使其无法输出Group(或文字testdata below:)。
相关问题