I have an XSLT 1.0 stylesheet that needs to either output the value of a specific element if that element exists, or output the string “NULL” if it doesn’t. How can I accomplish this?
Update
The document I’m working with looks something like this:
<kanjidic2>
<header>
<file_version>4</file_version>
<database_version>2010-325</database_version>
<date_of_creation>2010-11-20</date_of_creation>
</header>
<character>
<literal>亜</literal>
<codepoint>
<cp_value cp_type="ucs">4e9c</cp_value>
<cp_value cp_type="jis208">16-01</cp_value>
</codepoint>
</character>
<character>
<literal></literal>
<codepoint>
<cp_value cp_type="ucs">226F3</cp_value>
<cp_value cp_type="jis213">2-12-48</cp_value>
</codepoint>
</character>
<!-- Plus a few thousand more <character>s -->
</kanjidic2>
I’m writing an XSLT stylesheet to transform the above into a series of MySQL queries. Initially I wanted to output NULL if the character did not have a jis208 codepoint associated with it (hence my initial question), producing a query like this:
INSERT INTO `kanji` (`literal`, `ucs`, `jis208`, ...) VALUES ('亜', '4e9c', '16-01', ...);
INSERT INTO `kanji` (`literal`, `ucs`, `jis208`, ...) VALUES (', '226F3', NULL, ...);
I’ve since realised that I could make the XSLT simpler and produce a shorter query instead:
INSERT INTO `kanji` (`literal`, `ucs`, `jis208`, ...) VALUES ('亜', '4e9c', '16-01', ...);
INSERT INTO `kanji` (`literal`, `ucs`, `jis213`, ...) VALUES ('', '226F3', '2-12-48', ...);
The solution
<?xml version="1.0" encoding="UTF-8"?>
<stylesheet version="1.0" xmlns="http://www.w3.org/1999/XSL/Transform">
<output method="text" encoding="UTF-8"/>
<template match="/">
<apply-templates select="kanjidic2/character"/>
</template>
<template match="/kanjidic2/character">
<text>INSERT INTO `kanji` (`literal`</text>
<apply-templates select="codepoint/cp_value" mode="first"/>
<text>) VALUES ('</text>
<value-of select="literal"/>
<apply-templates select="codepoint/cp_value" mode="second"/>
<text>); </text>
</template>
<template match="/kanjidic2/character/codepoint/cp_value" mode="first">
<text>, `</text>
<value-of select="@cp_type"/>
<text>`</text>
</template>
<template match="/kanjidic2/character/codepoint/cp_value" mode="second">
<text>, '</text>
<value-of select="."/>
<text>'</text>
</template>
</stylesheet>
I will mark Dimitre Novatchev’s answer as the correct one because it is the most succinct solution to my initial question.
Thanks for your help.
This transformation:
when applied on the provided XML document:
produces the wanted, correct result:
When applied on this XML document:
again the wanted, correct result is produced:
Do note:
No conditional instruction (
<xsl:if>or<xsl:choose>/<xsl:when>/<xsl:otherwise>) is used at all.