-3

I am using a Web service and it returns a String value. But in my output, that value is in XML format:

String point = request.getParameter("point");
try {
  String latLonListCityNames = proxy.latLonListCityNames(new BigInteger(point));
  request.setAttribute("point", latLonListCityNames);
  System.out.println(latLonListCityNames);
} catch (RemoteException e) {
  e.printStackTrace();
}

I expect the output to be for example "Oklahoma", but the actual output is:

<?xml version='1.0' ?>
<dwml version='1.0' xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://graphical.weather.gov/xml/DWMLgen/schema/DWML.xsd">
    <latLonList>
    <cityNameList>
        Oklahoma
    </cityNameList>
</dwml>
Golov Pavel
  • 624
  • 5
  • 15
shamim
  • 47
  • 2
  • 6

1 Answers1

0

The responses of web-services are commonly (not always) in XML. If you need to extract the data from xml string response to your desired format, say, Java Objects (POJO), you need a converter i.e. marshaling and Un-marshaling of data.

Simple solution

Use JAXB.

What is JAXB? From wiki

Java Architecture for XML Binding (JAXB) is a software framework that allows Java developers to map Java classes to XML representations. JAXB provides two main features: the ability to marshal Java objects into XML and the inverse, i.e. to unmarshal XML back into Java objects.

How does it fit into my use-case?

Create a simple POJO for the type of response you are expecting. And then use JAXB convertor to convert them for you.

Eg. If you are expecting a list of cityName in response, you can create your POJO like below..

CityModel.java

public Class CityModel {
    private List<String> cityName;
    // if more field required, add here.
}

Sample XML response should be..

<ListOfCities>
    <CityName>My City</CityName>
    <CityName>Your City</CityName>
    <CityName>So Pity</CityName>
</ListOfCities>

Then, pass this xml response string to JAXB binding for Equivalent Class type. i.e. CityModel.

How to do all this? Can You Share some good example?

Read this tutorial to get started.

I have problem with the response type names, they are not well described, how can I map them with different name that I want?

You might need to look at links below, they key part is investigate more about @XmlRootElement, @XmlAttribute, @XmlElement, etc annotations for custom configurations.

Few more important links that can help later on?

Convert Soap XML response to Object

convert xml to java object using jaxb (unmarshal)

Using JAXB for XML With Java

JAXB Unmarshalling Example: Converting XML into Object

miiiii
  • 1,580
  • 1
  • 16
  • 29