0

I am trying to merge multiple XML files into one in the following manner:

Say I have an XML file, called fruit.xml:

<fruit>
    <apples>
        <include ref="apples.xml" />
    </apples>
    <bananas>
        <include ref="bananas.xml" />
    </bananas>
    <oranges>
        <include ref="oranges.xml" />
    </oranges>
</fruit>

and subsequent XML files that are referenced from fruit.xml, like for example apples.xml:

<fruit>
    <apples>
        <apple type="jonagold" color="red" />
        <... />
    </apples>
</fruit>

and so on... I would like to merge these into 1 XML file, like such:

<fruit>
    <apples>
        <apple type="jonagold" color="red" />
        <... />
    </apples>
    <bananas>
        <banana type="chiquita" color="yellow" />
        <... />
    </bananas>
    <oranges>
        <orange type="some-orange-type" color="orange" />
        <... />
    </oranges>
</fruit>

I want to determine the "child" files (like apples.xml, bananas.xml, etc.) dynamically based on the values of the ref attributes in the <include> elements of fruits.xml and then include them in the output.

Is this possible using XSLT?

pancake
  • 1,923
  • 2
  • 21
  • 42

1 Answers1

1

If only the contend of an file should be included you can use:

<xsl:copy-of select="document(@ref)/fruit/*/*"/>

Therefore try this:

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

    <xsl:output indent="yes" method="xml" encoding="utf-8" omit-xml-declaration="yes" />

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="include">
        <xsl:copy-of select="document(@ref)/fruit/*/*"/>
    </xsl:template>
</xsl:stylesheet>
hr_117
  • 9,589
  • 1
  • 18
  • 23
  • Thank you very much, it works! I am now trying to make it process `` elements in subsequent files as well, like so: `` instead of `` but the result is ``. Any tips? – pancake May 21 '13 at 18:39
  • Cancel that, already fixed it: I removed the `` element inside the ` – pancake May 21 '13 at 18:47
  • If you have to look at specific elements in your included files you can perhaps use applytemplates – hr_117 May 21 '13 at 18:47