3

I am using a JAX-WS service. Following is the part of request class.

@XmlElement(name = "Answers") 
protected String answers;

Now, in the actual SOAP request, the answers need to be sent in the xml as CDATA. There is a separate stub class for answers. Hence, I am marshalling the object of that class into an xml. I am surrounding this in CDATA tags as shown below:

xmlstr = "<![CDATA[" + xmlstr + "]]>"; 

Hence, my request xml should look like this:

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
    <!-- Other tags -->
    <Answers>
        <![CDATA[
            <TagOne></TagOne>
            <TagTwo></TagTwo>
        ]]>
    </Answers>
</S:Body>
</S:Envelope>

However, when the request is sent to server, from the SOAPLoggingHandler, it looks like this:

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
    <!-- Other tags -->
    <Answers>
        &lt;![CDATA[
            &lt;TagOne>&lt;/TagOne&gt;&#13;
            &lt;TagTwo>&lt;/TagTwo&gt;&#13;
        ]]&gt;&#13;
    </Answers>
</S:Body>
</S:Envelope>

Due to this escaping of characters, I am receiving the response saying "Invalid Answers xml format". I have 2 questions:

  1. Is xmlstr = "" the correct way to create a CDATA xml from a bean? If not then, is there any standard way to do that?

  2. If I want to send the CDATA section in request without escaping, which changes should I make into my implementation?

Let me know if anything else is required.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
  • Why does it need to be sent as a CDATA section? It should not matter how the data is represented in the XML (in CDATA or plain with special characters escaped with entities). – Henry Feb 06 '14 at 21:46
  • possible duplicate of [How to generate CDATA block using JAXB?](http://stackoverflow.com/questions/3136375/how-to-generate-cdata-block-using-jaxb) – kolossus Feb 07 '14 at 02:11

1 Answers1

-1

I think the situation here is your java object representation doesn't quite match what you'd like to see in the XML. And presume you use JAXB with JAX-WS, then you can create an adapter class for your element in the bean with XmlJavaTypeAdapter annotation.

public class CDATAAdapter extends XmlAdapter<String, String> {

  @Override
  public String marshal(String v) throws Exception {
    return "<![CDATA[" + v + "]]>";
  }

  @Override
  public String unmarshal(String v) throws Exception {
    return v;
  }
}

In your bean:

@XmlElement(name = "Answers")
@XmlJavaTypeAdapter(value=CDATAAdapter.class)
protected String answers;

For more details please read Using JAXB 2.0's XmlJavaTypeAdapter

Yuantao
  • 2,812
  • 1
  • 18
  • 19