teodron
teodron

Reputation: 1438

XSL replace entire node with data from another xml file

Input: two xml files. The first has several fields that contain relevant values, but an entire node is actually empty. The data for this node is contained within a second xml file.

Output: the first xml file containing the missing values taken from the second, supplied xml file.

Methodology: have to use an XSL file to perform the task of injecting the missing values in the first xml from the appropriate node in the second xml.

Example:

Main input.xml

<?xml version="1.0" encoding="UTF-16"?>
<root>
<data> a </data>
<values>
    <value>1</value>
    <value>2</value>
</values>
<objects></objects>
</root>

Source_of_missing_info.xml

<?xml version="1.0" encoding="UTF-16"?>
<root>
<data> a </data>
<values>
    <value>1</value>
    <value>2</value>
</values>
<objects>
    <object>Car</object>
    <object>Train</object>
    <object>Ship</object>
</objects>
</root>

Merger.xsl - this is required.

<?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:template match="/">
    <xsl:copy-of select="*"/>
</xsl:template>

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

   <xsl:template match="objects">
            <xsl:copy-of select="$lookup" />
            <xsl:value-of select="text()" />
   </xsl:template>

</xsl:stylesheet>

Expected output:

<?xml version="1.0" encoding="UTF-16"?>
<root>
<data> a </data>
<values>
    <value>1</value>
    <value>2</value>
</values>
<objects>
    <object>Car</object>
    <object>Train</object>
    <object>Ship</object>
</objects>
</root>

Is it possible to achieve the desired transform by modifying the above Merger.xsl? What is the key to the solution?

Upvotes: 0

Views: 927

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116992

Why not simply:

<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:strip-space elements="*"/>

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

<xsl:template match="objects">
    <xsl:copy-of select="document('input_missing.xml')/root/objects"/>
</xsl:template>

</xsl:stylesheet>

Upvotes: 2

Related Questions