I am transforming XML to XML using XSLT, The objective is to read the value of tag <node1>
, if it is null then it must be assigned with the value of <node2>
, if incase <node2>
, is also null, then default text "Default" has to be assigned .. to both tags ..
EDIT: If <node2>
is null and <node1>
isn t .. then the code shouldn t update <node2>
with Default
text but it has to be transformed as it is ..
This is the test XML I am trying with:
<root>
<node1></node1>
<node2></node2>
<parent>
<node1>data1</node1>
<node2></node2>
</parent>
<parent>
<node1></node1>
<node2>data2</node2>
</parent>
<parent>
<node1>data1</node1>
<node2>data2</node2>
</parent>
</root>
And this the XSLT code I have designed:
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template name="template1" match="node2[(following-sibling::node1[.= ]|preceding-sibling::node1[.= ])]">
<xsl:choose>
<xsl:when test=".= ">
<node1><xsl:text>Default</xsl:text></node1>
<node2><xsl:text>Default</xsl:text></node2>
</xsl:when>
<xsl:otherwise>
<node1>
<xsl:value-of select="text()"/>
</node1>
<xsl:copy>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="template2" match="node1[.= ]"/>
Though my code works, I am not happy with its bulkiness of the code .. Is there anyway to get rid of redundant (if any) lines .... And is there any alternative to use 2 templates to accomplish this (namely template1 and template2), is it possible to reduce the number of templates?