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
Xpath should be
.//ADDRESS/AddressLineText
A problem in your sample code is that in
<#list DEALS as d>
,DEALS
is the set ofDEALS
elements (which you have exactly 1). Same logic as in XSLT. Therefored
will be theDEALS
element, not aDEAL
element, andDEALS
has noPROPERTY
child. So what you want to list isDEALS.DEAL
, which is the set of all theDEAL
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 assumingbody
corresponds to the root element (MESSAGE
), maybe just use this:(If
body
is really the XML document instead, then of course you writebody.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).