I. XSLT 1.0 Solution:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:variable name="vReplacement">Default</xsl:variable> <xsl:variable name="vRep" select= "document('')/*/xsl:variable[@name='vReplacement']/text()"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="node1[not(node())] | node2[../node1[not(node())]]"> <xsl:copy> <xsl:copy-of select="../node2/text() | $vRep[not(current()/../node2/text())]"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
It is shorter and simpler than the current solutions - 7 lines less and , more importantly, one template less than the currently selected solution.
Even more important , this solution is fully declarative and push-style - without calling the named templates, and only <xsl:apply-templates> is in the identification rule.
II. XSLT 2.0 Solution
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="node1[not(node())] | node2[../node1[not(node())]]"> <xsl:copy> <xsl:sequence select="(../node2/text(), 'Default')[1]"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
Using the power of XPath 2.0 sequences, this solution is rather shorter than the XSLT 1.0 solution .
Something like this is not possible in XSLT 1.0 (for example, selecting the first one from the union of two nodes without specifying predicates to make the two nodes mutually exclusive), since a node with a default value of text and nodes node1 / node2 belong to different documents and, as we know , node ordering between nodes of different documents is implementation specific and not guaranteed / prescribed.
This solution is completely declarative (not if / then / else) and completely push: the identification rule uses only <xsl:apply-templates> .
source share