How to consume XML with more than one possible root element in Spring REST client

351 Views Asked by At

In my application I have to consume a service provided by a third party application. The response they provide is always 200 and they change the body based on whether data is available or not or error occurred, as given below

If data is there then

<products>
   <product></product>
   <product></product>
</products>

If data is empty then

<message> No record found </message>

If some validation failed then

<error>Invalid Id</error>

I am using RestTemplate.exchange to consume the service, my question is if there only single type of root element then we pass the respective class as ParameterizedTypeReference but here how to map the response and unmarshall it.

2

There are 2 best solutions below

0
On

Use jaxb or jackson to unmarshall the xml.

0
On

The right thing to do here is to ask the third party to change their service response to have a root tag. The response object would then look something like this:

<response>
<products>
   <product></product>
   <product></product>
</products>
<message> No record found </message>
<error>Invalid Id</error>
</response>

With this, you will only need to be concerned about response object and you can check the presence of respective sub-tags.

Other option to make this work for you is to do the exchange by passing String.class as the type reference. Then you would need to do the check in your code to see if the string response returned is products or message or error