Merging 2 documents, joining on a unique ID
My goal is to merge two xml documents so that a specific node and its children are replaced with the contents of another in the second xml document. *It seems to be working with one problem(see bottom). It's hard for me to explain cause I'm newby:)
Here's the code:
<users>
<user uid="1">
<fname>John</fname>
<lname>Smith</lname>
<phone>1111111111</phone>
</user>
<user uid="2">
<fname>Dave</fname>
<lname>Black</lname>
<phone>2222222222</phone>
</user>
</users>
<users>
<user uid="2">
<fname>Sam</fname>
<lname>Gold</lname>
<phone>3333333333</phone>
</user>
</users>
<users>
<user uid="1">
<fname>John</fname>
<lname>Smith</lname>
<phone>1111111111</phone>
</user>
<user uid="2">
<fname>Sam</fname>
<lname>Gold</lname>
<phone>3333333333</phone>
</user>
</users>
<!--
The problem is with the John Smith record(the one that doesn't get the update...the <user uid="1"> is missing. Do I have to manually write this out in my <xsl:otherwise> element...maybe because I'm inside the user node already?-->
-->
<users>
<notupdated>
<fname>John</fname>
<lname>Smith</lname>
<phone>1111111111</phone>
</notupdated>
<updated><user uid="2">
<fname>Sam</fname>
<lname>Gold</lname>
<phone>3333333333</phone>
</user>
</updated>
</users>
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:variable name="doc-file">documentupdate.xml</xsl:variable>
<xsl:template match="* | @*">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="users/user">
<xsl:param name="userID">
<xsl:value-of select="@uid"/>
</xsl:param>
<xsl:choose>
<xsl:when test="document($doc-file)//users/user[@uid=$userID]">
<updated><xsl:copy-of select="document($doc-file)//users/user"/></updated>
</xsl:when>
<xsl:otherwise>
<notupdated>
<xsl:apply-templates/>
</notupdated>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
|