Drikus
Drikus

Reputation: 11

How do I merge a couple of xml files into one xml file using xslt?

I need to merge a couple of XML files in to one, using XSLT. I have 4 XML files release, reception, theatre1 and theatre2. release has to be added first then its matching reception has to be placed inside of the release part. The other two should then be added.

here is the format of the files. release: text

reception: text

result should be: < text text

Here is what I have so far, but it doesn't work completely

The other 2 files just need to be added at the end

Upvotes: 1

Views: 1324

Answers (2)

Lumi
Lumi

Reputation: 15264

Here's how to proceed:

$ expand -t2 release.xml
<release name="bla"/>

$ expand -t2 reception.xml
<receptions>
  <reception name="bla">
    <blabla/>
  </reception>
  <reception name="blub">
    <blubbel/>
  </reception>
</receptions>

$ expand -t2 theatre1.xml
<theatre number="1"/>

$ expand -t2 theatre2.xml
<theatre number="2"/>

$ expand -t2 release.xsl
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:strip-space elements="*"/><!-- make output look nice -->
  <xsl:output indent="yes"/>

  <xsl:template match="release">
    <xsl:variable name="rel-name" select="@name"/>
    <xsl:copy>
      <xsl:copy-of select="node()"/><!-- copy remainder of doc -->
      <xsl:copy-of select="document( 'release.xml' )"/>
      <xsl:variable name="rcpt-doc" select="document( 'reception.xml' )"/>
      <xsl:copy-of select="$rcpt-doc/*/reception[ @name = $rel-name ]"/>
      <xsl:copy-of select="document( 'theatre1.xml' )"/>
      <xsl:copy-of select="document( 'theatre2.xml' )"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

Call it like this:

 xsltproc release.xsl release.xml

This is the result:

<?xml version="1.0"?>
<release>
  <release name="bla"/>
  <reception name="bla">
    <blabla/>
  </reception>
  <theatre number="1"/>
  <theatre number="2"/>
</release>

Upvotes: 3

Crypth
Crypth

Reputation: 1642

Reading Multiple Input Documents seems to answer this question.

When you run an XSLT processor, you tell it where to find the source tree document -- probably in a disk file on a local or remote computer -- and the stylesheet to apply to it. You can't tell the processor to apply the stylesheet to multiple input documents at once. The document() function, however, lets the stylesheet name an additional document to read in. You can insert the whole document into the result tree or insert part of it based on a condition described by an XPath expression. You can even use this function with the xsl:key instruction and key() function to look up a key value in a document outside your source document.

Hence, the key to load multiple documents in xslt is using the document() function.

Upvotes: 2

Related Questions