Evgeni Dimitrov Evgeni Dimitrov - 3 months ago 10
Java Question

CXF SOAP service preserve space

I have CXF soap web service.

@Component
@WebService(endpointInterface = "com....MyWs", serviceName="MySrv")
public class MyWsImpl implements MyWs {
@Override
public List<MyModel> get(String customer) {
List<MyModel> models = ...;
return models;
}
}


There is a filed in MyModel that can be a space (
" "
), but the parser trims the value and it's serialized as
<mySpaceVal></mySpaceVal>
wile I want
<mySpaceVal> </mySpaceVal>


How can I do that?

I tried to add

@XmlAttribute(name="space", namespace="xml")
public final static String space = "preserve";


to MyModel so the parser can add xml:space="preserve" attribute.
But it adds a namespace
ns3="xml"
and displays the attribute as
ns3:space="preserve"
and the element is displayed as an empty string instead of
" "

Answer

You can wrap your string value in <![CDATA[]]> section using jaxb adapter:

@XmlJavaTypeAdapter(CDATAXmlAdapter.class)
public final static String space = "...";

private static class CDATAXmlAdapter extends XmlAdapter<String, String> {
    @Override
    public String marshal(final String value) throws Exception {
        // you may want to apply additional value escaping to avoid
        // CDATA nesting problem
        return "<![CDATA[" + value + "]]>";
    }

    @Override
    public String unmarshal(final String value) throws Exception {
        // If you expect that server will send CDATA as well
        // then you need to strip CDATA from value
        return value;
    }
}
Comments