Search code examples
xmlfreemarker

How do you match more than one node using Freemarker?


My FreeMarker FTL code is the following:

<a class="launch" href="${item.target-url}">View Now</a>

I am pulling a snippet from the following XML:

<item>
 <target-url>www.test.com/jimmy</target-url>    
</item>
<item>
 <target-url></target-url>  
</item>
<item>
 <target-url></target-url>  
</item>

I figure that this should work.

But when I view my html page I get the following error:

Exception when trying to transform with the FTL template! freemarker.core.NonNumericalException: For "-" left-hand operand: Expected a number, but this evaluated to a sequence+hash (wrapper: f.e.dom.NodeListModel): ==> item.target [in template "marketing/widgets/freemarker/newblogpost-update.ftl" at line 31, column 105] ---- 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. That is, the constructing XML query has found no matches. ---- ---- FTL stack trace ("~" means nesting-related): - Failed at: ${item.target - url?size != 0} [in template "marketing/widgets/freemarker/newblogpost-update.ftl" at line 31, column 103] ----

I figure that I am getting this error because my XML contains multiple nodes () that don't contain data. Some of my nodes may contain data but not all of them. Is there a way that I can fix this?


Solution

  • You are getting an error because you have - sign in XML tag and FreeMarker treats it like a minus sign: ${item.target - key}

    So you have to use that construction:

    ${item["target-url"]}
    

    FAQ