×

Please give details of the problem

Skip to content

How to deal with the result of a webservice regardless of its structure

An atom return of a web service is interpreted in Freemarker which can yield different structures depending on the number of entries. It may be convenient to parse the result and generate an array in all cases. To such an extent, you can use the following method:

${P_to_array(P_result.feed, "entry")}

This will return an array if there is 0, 1 or several entries.

See how it works:

Case 1 : There are several entries

Raw P_result as xml

<feed>
    <entry>
        <title>John</title>
    </entry>
    <entry>
        <title>Mathew</title>
    </entry>
</feed>

Parsed P_result as tree

parsing_xml_example

Parsed P_result as string : P_result.feed.entry is an array

{ "feed": { "entry": [ {"title": "John"}, {"title": "Mathew"} ]} }
<#assign my_entries = P_to_array(P_result.feed, "entry")>
${my_entries}

Result of P_to_array as tree

parsing_xml_example

Result of P_to_array as string

[ { "title":"John" }, { "title":"Mathew" } ]

Case 2 : There is only one entry

Raw P_result as xml

<feed>
    <entry>
        <title>John</title>
    </entry>
</feed>

Parsed P_result as tree

parsing_xml_example

Parsed P_result as string : P_result.feed.entry is not an array but a json

{ "feed": { "entry": {"title":"John"} } }
<#assign my_entries = P_to_array(P_result.feed, "entry")>
${my_entries}

Result of P_to_array as tree

parsing_xml_example

Result of P_to_array as string

[ { "title": "John" } ]

Case 3 : There is no entry

Raw P_result as xml

<feed>

</feed>

Parsed P_result as tree

parsing_xml_example

Parsed P_result as string : P_result.feed.entry does not exist

{ "feed": {""} }
<#assign my_entries = P_to_array(P_result.feed, "entry")>
${my_entries}

Result of P_to_array as tree

parsing_xml_example

Result of P_to_array as string

[]