Question

I am using JAX-WS with the JAX-WS reference implementation. I'm creating a Web Service that gets XML to store and later can return that previously stored XML.

@WebMethod(operationName="store")
public void store(@WebParam(name="XML") String XML)
{
  ...
}

@WebMethod(operationName="retrieve")
public String retrieve()
{
  String s = XML;
  return s;
}

My Interface uses the type String for the XML. When I send the XML data, I wrap the whole string into a CDATA-Tag (since I need to send characters like < and > within the soap message). However when the Web Service later returns that XML data, strange things happen:

If the string is long enough, the WS wraps everything into CDATA, that's the way I want it.

However if the string is really short (e.g. small XML instances), the single characters are escaped (e.g. < becomes &lt;). This is NOT what I want because it makes it really hard to work with the data. Besides, if my string contains characters like & because I stored escaped text, this gets killed and becomes &amp;

How can I force my Web Service to return the string always within CDATA and not escape anything by itself? Simply appending <![CDATA[ and ]]> before and after the string right before returning the value does not help because the CDATA-Markup itself then gets escaped.

BTW: I think the fact that I store and retrieve XML does not even matter. The same would be the problem if I store usual strings containing characters like '<', '>' and '&' (which is essentially what I do). If I store them via CDATA but do not get them back via CDATA but with every single special characters escaped independently, I have to reconstruct the whole string by myself. How can I enforce the use of CDATA when returning strings?

Was it helpful?

Solution

While I agree with @Henry that it should just work (especially since your type is String), if you have some special case where you really need CDATA wrapping regardless:

I think you'll have to create a SOAPHandler (lots of resources out there on doing so). Find the element that contains your data. Get the text content and XML decode that back into your "normal" string. See the "Create a CData Section Node" here: http://www.w3schools.com/dom/dom_nodes_create.asp. Remove the text from the element, create and add the CData node with your content, and that should work fine.

You can theoretically also do so via JAXB (How to generate CDATA block using JAXB?) - just found the link, haven't tried it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top