Reputation: 797
I have the following XMLs:
car.xml:
<car ref-id="parts.xml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<color>red</color>
<tire>michelin</tire>
<engines>
<engine>
<model>Z</model>
</engine>
</engines>
<hifi>pioneer</hifi>
</car>
parts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<parts xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<engines>
<engine>
<model>X</model>
</engine>
<engine>
<model>Y</model>
</engine>
</engines>
<tire>goodyear</tire>
<color>black</color>
<airbag>true</airbag>
</parts>
I'd like to merge parts.xml with car.xml, but want to copy only those nodes from parts.xml (regardless of their value) which doesn't exist in car.xml.
E.g, I'd need the following output:
<car xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<color>red</color>
<tire>michelin</tire>
<engines>
<engine>
<model>Z</model>
</engine>
</engines>
<hifi>pioneer</hifi>
<airbag>true</airbag>
</car>
I'm stuck at the following transformation which merges all the elements:
<?xml version="1.0"?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" />
<xsl:variable name="loc">
<xsl:value-of select="car/@ref-id" />
</xsl:variable>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="car">
<xsl:copy>
<xsl:apply-templates select="@*|node() | document($loc)/parts/*" />
</xsl:copy>
</xsl:template>
</xsl:transform>
Upvotes: 0
Views: 413
Reputation: 116982
That's a rather awkward arrangement to have, and the solution - at least in XSLT 1.0 - is no less awkward:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
extension-element-prefixes="exsl">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/car">
<xsl:variable name="local-names">
<xsl:for-each select="*">
<name><xsl:value-of select="name()"/></name>
</xsl:for-each>
</xsl:variable>
<xsl:copy>
<xsl:copy-of select="*"/>
<xsl:copy-of select="document(@ref-id)/parts/*[not(name()=exsl:node-set($local-names)/name)]"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Upvotes: 1