javaxmlfreemarkersmooks

Freemarker - <#if ??> doesn't seem to work in identifying null objects


I am trying XML-XML transformations using FreeMarker. What is the correct way to handle null objects. (Not values but null objects)

When "AlertIndicator" tag is not present in the input XML, how can i handle it. I tried all these combinations, but none seem to work :(

 <#if Response.Variables.AlertIndicator??>${Response.Variables.AlertIndicator}<#else></#if>
<#if (Response.Variables.AlertIndicator)??>${Response.Variables.AlertIndicator}<#else></#if>

${Response.Variables.AlertIndicator!""}
 ${(Response.Variables.AlertIndicator)!""}

All of these give me an exception

Expected a string or something automatically convertible to string (number, date or boolean), but this evaluated to a sequence+hash
Tip: This XML query result can't be used as string because for that it had to contain exactly 1 XML node, but it contains 0 nodes

The only thing that seems to be is "has_content" but it takes twice as long to process which is a big NO for my application


Solution

  • The result of a DOM query is always a list of nodes, even if possibly a 0-length list. The result node list itself always exists, so Response.Variables.AlertIndicator?? is always true. (This also means that that query will work the same if there are no Variables and if there are no AltertIndicators, i.e., you can chain the steps safely.) So you have to check if the 1st node in the result list exists: Response.Variables.AlertIndicator[0]??