Search code examples
xmlfreemarker

How to check empty node using FreeMarker


I can't find the right build-in function to check if a node is empty.
Here is the xml sample node -

<address>
    <street1/>
    <street2/>
    <city/>
    <zip/>
    <country>BD</country>
</address>

I have tried using adr.street1?has_content but this does not returns false since the node is present.

<#list address as adr>
    <#if adr.street1?exists && adr.street1?has_content>
        street1 is present //this line executes but it shouldn't be since street1 has no value.
    </#if>
</#list>

Solution

  • adr.street1 is a sequence that contains a single node, so it "has content". Furthermore any subvariable query (. or [...]) just gives a sequence of matching nodes, never the node itself. (So for example, if you have only one street1, arr.street1[0] just gives back the original sequence. Which can be quite surprising, but it's just the approach of XPath.)

    So, do this check: adr.street1?children?has_content. Because the number of children is 0. If street1 can only contain text, then this is nicer: adr.street1 != ''.

    You do not need existence checks, like ! or ?exists, because XML queries are guaranteed to return some result. If there's no match, it's just an empty sequence.