×

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 interpretated 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 extent, you can use the following method :

1
${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

1
2
3
4
5
6
7
8
    <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

1
    {"feed":{"entry":[{"title":"John"},{"title":"Mathew"}]}}
1
2
    <#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

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

Case 2 : There is only one entry

Raw P_result as xml

1
2
3
4
5
    <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

1
    {"feed":{"entry":{"title":"John"}}}
1
2
    <#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

1
    [{"title":"John"}]

Case 3 : There is no entry

Raw P_result as xml

1
2
    <feed>
    </feed>

Parsed P_result as tree

parsing_xml_example

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

1
    {"feed":{""}}
1
2
    <#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

1
    []