Reputation: 78
This should be simple, but I am unable to figure this one out. I have XML files that contain some empty nodes that I want to replace with a fixed string via XSL. If the node contains data it is fine, but if it is empty I want to replace it with a string "18010101"
For Example:
Before:
<?xml version="1.0"?>
<TopNode>
<SubNode1>
<SubNode2>
<SubNode3>
<SubNode4>
<date_of_birth></date_of_birth>
</SubNode4>
</SubNode3>
</SubNode2>
</SubNode1>
</TopNode>
After:
<?xml version="1.0"?>
<TopNode>
<SubNode1>
<SubNode2>
<SubNode3>
<SubNode4>
<date_of_birth>18010101</date_of_birth>
</SubNode4>
</SubNode3>
</SubNode2>
</SubNode1>
</TopNode>
I have a similar issue where I replace a fixed value with another fixed value with xsl.
<xsl:template match="transaction_type[text()='15']">
<xsl:text>5</xsl:text>
</xsl:template>
It works fine, but when I try to do a similar fix for the date issue it doesn't seem to work.
<xsl:template match="date_of_birth">
<xsl:if test="date_of_birth = ''">
<xsl:text>18010101</xsl:text>
</xsl:if>
</xsl:template>
Thanks
Upvotes: 2
Views: 2389
Reputation: 4739
Change your xsl:if
to:
<xsl:if test=". = ''">
Or change your xsl:template match
to:
<xsl:template match="date_of_birth[. = '']">
Upvotes: 3
Reputation: 8050
I would simply do this,
XML:
<?xml version="1.0"?>
<TopNode>
<SubNode1>
<SubNode2>
<SubNode3>
<SubNode4>
<date_of_birth></date_of_birth>
</SubNode4>
</SubNode3>
</SubNode2>
</SubNode1>
</TopNode>
XSL:
<?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="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* , node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="date_of_birth">
<xsl:if test=". = ''">
<date_of_birth>18010101</date_of_birth>
</xsl:if>
<xsl:if test=". != ''">
<date_of_birth>
<xsl:value-of select="text()" />
</date_of_birth>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Output:
<?xml version="1.0" encoding="UTF-8"?>
<TopNode>
<SubNode1>
<SubNode2>
<SubNode3>
<SubNode4>
<date_of_birth>18010101</date_of_birth>
</SubNode4>
</SubNode3>
</SubNode2>
</SubNode1>
</TopNode>
Upvotes: 0