Merge two differently-formatted XML files with XSLT by matching id

One of my XMLs is like this:

<people>
    <person code="111" name="Bob" />
    <person code="222" name="Sue" />
</people>

And the other is like this:

<people>
    <person>
        <id>111</id>
        <age>80</age>
    </person>
    <person>
        <id>222</id>
        <age>73</age>
    </person>
</people>

The "code" from the first file is the same as the "id" from the second file.

I would like to merge these two to get this:

<people>
    <person>
        <id>111</id>
        <name>Bob</name>
        <age>80</age>
    </person>
    <person>
        <id>222</id>
        <name>Sue</name>
        <age>73</age>
    </person>
</people>

How can I do this with XSLT?

Answers


If the first person files have all person ids you care about, you can do something like this.

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
            >
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="person">
        <person>
            <id>
                <xsl:value-of select="@code"/>
            </id>
            <name>
                <xsl:value-of select="@name"/>
            </name>
            <xsl:for-each select="document('ip2.xml')//person[id=current()/@code]">
                <xsl:apply-templates  />
            </xsl:for-each>
        </person>
    </xsl:template>
    <xsl:template match="id" />
    <xsl:template match="node() | @*">
        <xsl:copy>
        <xsl:apply-templates    />
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Which will generate this output:

<?xml version="1.0"?>
<people>
    <person>
        <id>111</id>
        <name>Bob</name>
        <age>80</age>
    </person>
    <person>
        <id>222</id>
        <name>Sue</name>
        <age>73</age>
    </person>
</people>

Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.