Thursday, December 10, 2009

Send XML data over web service

Occasionally I am being asked a common question, "How to send XML data over web service?". In Java (in fact in any programming language) XML is just a string (sequence of characters). So sending XML as request parameter or receiving it in response is just like handling any other string data.

For the following XML data from web service client and server-

XML from client
<name>vinod</name>

XML from server
<greeting>Hello! vinod</greeting>

This is the web service (JAX-WS) request and response-
REQUEST
<?xml version="1.0" ?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <ns2:xmlData xmlns:ns2="http://vinodsingh.com">
            <data>&lt;name&gt;vinod&lt;/name&gt;</data>
        </ns2:xmlData>
    </S:Body>
</S:Envelope>

RESPONSE
<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <ns2:xmlDataResponse xmlns:ns2="http://vinodsingh.com">
            <return>&lt;greeting>Hello! vinod&lt;/greeting></return>
        </ns2:xmlDataResponse>
    </S:Body>
</S:Envelope>

The above example clearly shows that JAX-WS runtime handles XML strings pretty well. The source code available here includes an example of sending bigger XML data.

3 Comments: