Join two XML files using XSL Transformation

This blog demonstrates how you can JOIN (yes, like in SQL) two xml (datasets) to one using a common ID (relationship).

shop.xml


<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type='text/xsl' href='main.xsl'?>
<shop>
<product>
<id>100</id>
<title>hello</title>
</product>

<product>
<id>101</id>
<title>world</title>
</product>
<product>
<id>102</id>
<title>praveen</title>
</product>
</shop>

price.xml

<?xml version="1.0" encoding="UTF-8"?>
<shop>
<product>
<id>100</id>
<price>10.0</price>
</product>
<product>
<id>101</id>
<price>10.1</price>
</product>
<product>
<id>102</id>
<price>10.2</price>
</product>
<product>
<id>103</id>
<price>10.3</price>
</product>

</shop>

main.xsl


<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />

<xsl:param name="fileName" select="'price.xml'" />

<xsl:variable name="updateItems" select="document($fileName)/shop/product" />

<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
<xsl:copy-of select="$updateItems[id=current()/id]/price" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>

Resulting XML, after transformation should look like:


<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type='text/xsl' href='main.xsl'?>
<shop>
<product>
<id>100</id>
<title>hello</title>
<price>10.0</price>
</product>
<product>
<id>101</id>
<title>world</title>
<price>10.1</price>
</product>
<product>
<id>102</id>
<title>praveen</title>
<price>10.2</price>
</product>
</shop>

Bonus code, if some .net developers want a transformation code:


XslTransform xslt = new XslTransform();
xslt.Load(@"D:\Websites\xmltest\main.xsl");
xslt.Transform(@"D:\Websites\xmltest\shop.xml", @"D:\Websites\xmltest\out.xml");
textBox1.Text = System.IO.File.ReadAllText(@"D:\Websites\xmltest\out.xml");