javaxmlapachevelocityapache-velocity

How to generate self closing XML elements using Apache Velocity template, if the value is null or empty


Is there any shorter way to generate xml elements using Apache Velocity, with elements with self closing tags if the value is null or empty.

However this can be achieved by putting - #if #else #end. but I need some shorter way to do this as I need to use it multiple places in template.

            #if( $stu.libno )
                <libno>$stu.libno</libno>
            #else
                <libno />
            #end

Solution

  • It seems a good use case for a macro:

    #macro( optionalTag $tagName $value )
      #if( $value )
        <$tagName>$value</$tagName>
      #else
        <$tagName/>
      #end
    #end
    

    which you can define at the beginning of your templates, or in the shared global macro library file. Then, you can do:

    #optionalTag( 'libno', $stu.libno )