keanu
keanu

Reputation: 123

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

Upvotes: 1

Views: 1051

Answers (2)

ddekany
ddekany

Reputation: 31162

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]??

Upvotes: 1

Oleg
Oleg

Reputation: 6324

You can use ?size which will be greater than 0 when the tag exists:

<#if Response.Variables.AlertIndicator?size gt 0>${Response.Variables.AlertIndicator}</#if>

Not sure if it will be faster than ?has_content though, you will need to check and if not, optimize it in a different way. Assigning to a variable before checking is a simple optimization.

<#assign x=Response.Variables.AlertIndicator>
<#if x?size gt 0>${x}</#if>

Upvotes: 1

Related Questions