xmlxsltrecursionfile-inclusion

How can I write an XSLT that will recursively include other files?


Let's say I have a series of xml files in this format:

A.xml:

<page>
    <header>Page A</header>
    <content>blAh blAh blAh</content>
</page>

B.xml:

<page also-include="A.xml">
    <header>Page B</header>
    <content>Blah Blah Blah</content>
</page>

Using this XSLT:

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/page">
        <h1>
            <xsl:value-of select="header" />
        </h1>
        <p>
            <xsl:value-of select="content" />
        </p>
    </xsl:template>
</xsl:stylesheet>

I can turn A.xml into this:

<h1>
    Page A
</h1>
<p>
    blAh blAh blAh
</p>

But how would I make it also turn B.xml into this?

<h1>
    Page B
</h1>
<p>
    Blah Blah Blah
</p>
<p>
    blAh blAh blAh
</p>

I know that I need to use document(concat(@also-include,'.xml')) somewhere, but I'm not sure where.


Oh, and the catch is, I need this to still work if B were to be included in a third file, C.xml.

Any idea as to how to do this?


Solution

  • It is possible:

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    
      <xsl:template match="page">
        <h1>
          <xsl:value-of select="header"/>
        </h1>
        <p>
          <xsl:apply-templates select="." mode="content"/>
        </p>
      </xsl:template>
    
      <xsl:template match="page" mode="content">
        <xsl:value-of select="content"/>
        <xsl:if test="@include">
          <xsl:apply-templates select="document(@include)" mode="content"/>
        </xsl:if>
      </xsl:template>
    
    </xsl:stylesheet>