xsl-list
[Top] [All Lists]

RE: Arbitrary XML document merge and styling with XSLT

2003-07-17 22:15:45
Scott Powell wrote:

Let's say page.xml lists all the xml files to merge
(see below); the mode node indicates which template
mode to use in the transformation file.  Page.xsl
contains the transformation instructions, making the
appropriate document() calls as needed.

But I've discovered that apply-templates' mode=""
value must be a constant.  All my efforts to use the
mode value from page.xml have fallen over.

Is there a way to do this sort of "generic" merge
within a single xsl file without hard-coding the match
logic or using xsl:if's?

<snip/>

======================================================
page.xml (contains a list of xml files to merge along
with a MODE element I'd like to use to dictate which
templates should be applied in the page.xsl file)
======================================================
<?xml version="1.0" encoding="UTF-8"?>
<page>
  <element>
    <mode>main</mode>
    <file>main_menu.xml</file>
  </element>
  <element>
    <mode>left</mode>
    <file>left_menu.xml</file>
  </element>
</page>

One way to do this is to transform your page.xml into an xml stylesheet
(using a "meta-stylesheet"), and then run THAT. This may not be feasible
depending on your execution environment, but if you can swing it, it will do
everything you want very simply. NB you will have to use the namespace alias
feature so that the meta-stylesheet can output elements in the xsl
namespace.

Transform the <page> into an <xsl:stylesheet> containing a template matching
"/".
Transform each <element> into an <xsl:apply-templates> element.

e.g. apply the following XSLT to your page.xml:

<xsl:stylesheet version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
        xmlns:output-xsl="xsl-alias"

        <xsl:namespace-alias stylesheet-prefix="output-xsl" 
result-prefix="xsl"/>

        <xsl:template match="page">
                <output-xsl:stylesheet version="1.0">
                        <output-xsl:template match="/">
                                <xsl:apply-templates/>
                        </output-xsl:apply-templates>
                </output-xsl:stylesheet>
        </xsl:template>

        <xsl:template match="element">
                <output-xsl:apply-templates select="document('{file}')" 
mode="{mode}"/>
        </xsl:template>

</xsl:stylesheet>

... this produces the following stylesheet:

<output-xsl:stylesheet
xmlns:output-xsl="http://www.w3.org/1999/XSL/Transform"; version="1.0">
   <output-xsl:template match="/">
      <output-xsl:apply-templates mode="main"
select="document('main_menu.xml')" />
      <output-xsl:apply-templates mode="left"
select="document('left_menu.xml')" />
   </output-xsl:template>
</output-xsl:stylesheet>

Cheers

Con


 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list