How to merge two XML documents?

H

Hvid Hat

How can I merge the following two XML documents:

Persons.xml
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person>
<name>Albert</name>
<department_id>1</department_id>
</person>
<person>
<name>Barry</name>
<department_id>2</department_id>
</person>
<person>
<name>Charlie</name>
<department_id>3</department_id>
</person>
</persons>

Departments.xml
<?xml version="1.0" encoding="UTF-8"?>
<departments>
<department>
<id>1</id>
<name>Management</name>
</department>
<department>
<id>2</id>
<name>Sales</name>
</department>
<department>
<id>3</id>
<name>Support</name>
</department>
</departments>

To generate the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person>
<name>Albert</name>
<department>Management</department>
</person>
<person>
<name>Barry</name>
<department>Sales</department>
</person>
<person>
<name>Charlie</name>
<department>Support</department>
</person>
</persons>
 
M

Mukul Gandhi

Please try this stylesheet (by applying to, Persons.xml):

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

<xsl:eek:utput method="xml" indent="yes" />

<xsl:variable name="dep" select="document('Departments.xml')" />

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

<xsl:template match="department_id">
<xsl:variable name="dep_id" select="." />
<department>
<xsl:value-of select="$dep/departments/department[id = $dep_id]/
name" />
</department>
</xsl:template>

</xsl:stylesheet>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top