I have a source document:
<?xml version="1.0"?>
<source>
<ItemNotSubstituted/>
<ItemToBeSubstituted Id='MatchId' />
</source>
And a stylesheet containing content I want to substitute into the source:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" method="xml" omit-xml-declaration="no" version="1.0"/>
<xsl:preserve-space elements="//*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="ItemToBeSubstituted[@Id = 'MatchId']">
<xsl:copy>
<xsl:copy-of select="@*|*"/>
<Element1/>
<Element2 Value="foo"/>
<Element3 Value="bar"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
This stylesheet succesfuly copies <Element1/><Element2 Value="foo"/><Element3 Value="bar"/>
into ItemToBeSubstituted
. But when I use a different source document, in which ItemToBeSubstituted
already has content:
<?xml version="1.0"?>
<source>
<ItemNotSubstituted/>
<ItemToBeSubstituted Id='MatchId'>
<Element3 Value="baz"/>
</ItemToBeSubstituted>
</source>
I get this output:
<?xml version="1.0"?>
<source>
<ItemNotSubstituted/>
<ItemToBeSubstituted Id="MatchId">
<Element3 Value="baz"/>
<Element1/>
<Element2 Value="foo"/>
<Element3 Value="bar"/>
</ItemToBeSubstituted>
</source>
I would like to only substitute elements from the stylesheet that do not already exist in the source document. This is the output I'm looking for after applying the stylesheet to the second document, with only the <Element3>
element from the source document:
<?xml version="1.0"?>
<source>
<ItemNotSubstituted/>
<ItemToBeSubstituted Id="MatchId">
<Element3 Value="baz"/>
<Element1/>
<Element2 Value="foo"/>
</ItemToBeSubstituted>
</source>
What is the best approach for doing this with XSL? The stylesheet may contain many elements to be substituted. So I don't want to use an approach that requires an <xsl:if>
around every single element. Is there a better way than using one stylesheet to insert the content, then having a second stylesheet that removes duplicate elements?