skip to Main Content

I am trying to create a Freemarker program to convert XML to JSON . I am not able to read values from the list of values from the repeated tags of a xml .
Am not able to figure out why i could not read value from repeated tags .

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

}

<MESSAGE>
<DEAL_SETS>
    <DEALS>
        <DEAL>
         <PROPERTY>
        <ADDRESS>
         <AddressLineText>1111</AddressLineText>
        </ADDRESS>
        </PROPERTY>
        </DEAL>
        <DEAL>
         <PROPERTY>
        <ADDRESS>
         <AddressLineText>2222</AddressLineText>
        </ADDRESS>
        </PROPERTY>
        </DEAL>
        <DEAL>
         <PROPERTY>
        <ADDRESS>
         <AddressLineText>3333</AddressLineText>
        </ADDRESS>
        </PROPERTY>
        </DEAL>
    </DEALS>
</DEAL_SET>
</MESSAGE>

Output
{
 "loans": []
}

Expected output
{
"loans": [
{propAddress1: 1111},
{propAddress1: 2222},
{propAddress1: 3333}
]
}

2

Answers


  1. Xpath should be .//ADDRESS/AddressLineText

    Login or Signup to reply.
  2. A problem in your sample code is that in <#list DEALS as d>, DEALS is the set of DEALS elements (which you have exactly 1). Same logic as in XSLT. Therefore d will be the DEALS element, not a DEAL element, and DEALS has no PROPERTY child. So what you want to list is DEALS.DEAL, which is the set of all the DEAL elements inside the (single) DEALS elements.

    Also I’m not sure why you are using //. It works, but generally you care what the parents are, so assuming body corresponds to the root element (MESSAGE), maybe just use this:

    {
      loans:  [
      <#list body.DEAL_SETS.DEALS.DEAL as DEAL>
        {
          propAddress1: ${DEAL.PROPERTY.ADDRESS.AddressLineText}
        }
      </#list>
      ]
    }
    

    (If body is really the XML document instead, then of course you write body.MESSAGES.DEAL_SETS.DEALS.DEAL instead.)

    Also, you probably want to quote the address, for which you can use <#ftl output_format="JSON"> on the top, and then ${DEAL.PROPERTY.ADDRESS.AddressLineText?c} (this requires FreeMarker 2.3.32).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search