xpathfreemarker

How to separate XML tags in freemarker in body function


I am trying to write a freemarker function to parse xml but i want to avoid the specific XPATH set from the xml.

The below freemarker is working if the xml does not have DOCUMENT_SETS . But my xml comes with DOCUMENT_SETS and i could not avoid those tags when i am calling body["MESSAGE//DEALS"]. My list is empty when xml have DOCUMENT_SETS tag in the below xml.

<#assign DEALS = body["MESSAGE//DEALS"]>
{
loans:[
 <#list DEALS as d>
    {
        Address1 : ${d[".//AddressLineText"]}
    }
 </#list>       
    ]
}

Sample xml

<MESSAGE >
 <DEALS>
    <DEAL>
        <AddressLineText>Addr1</AddressLineText>
    </DEAL>
    <DEAL>
        <AddressLineText>Addr2</AddressLineText>
    </DEAL>
  </DEALS>
  <DOCUMENT_SETS>
    <DEALS>
        <DEAL>
            <LateChargeAmount>110</LateChargeAmount>
        </DEAL>
    </DEALS>
 </DOCUMENT_SETS>
 </MESSAGE>

How i can get DEAL only under MESSAGE//DEALS , i totally want to avoid DOCUMENT_SETS tag.

Expected output

{
 "loans": [
  {
  AddressLineText : Addr1
  },
  {
   AddressLineText : Addr2
  }
  ]
  }

Solution

  • Try changing your template to

    <#assign DEALS = someXML["MESSAGE//DEALS[following-sibling::DOCUMENT_SETS]/DEAL"]>
        {
        loans:[
         <#list DEALS as d>
            {
                 ${d["name(./*)"]} : ${d["./AddressLineText"]}
                 # or ${d["name(./*)"]} : ${d["./*"]}
            }
         </#list>       
            ]
        }
    

    The output I get, based on your sample xml is:

    {
    loans:[
        {
             AddressLineText : Addr1
        }
        {
             AddressLineText : Addr2
        }
        ]
    }