How can SOAPMessage parse <![CDATA[ ]]>?

2.3k views Asked by At

Here is the code which marshals java object into a SOAPMessage:

     public static SOAPMessage encode(String key,Object object) throws JAXBException, SOAPException{
 JAXBContext airContext = newInstance("com.test");
        contextMap.put("ws", airContext);
        Marshaller marshaller = airContext .createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage message = messageFactory.createMessage();
        marshaller.marshal(object, message.getSOAPBody());
        message.saveChanges();
        return message;
    }

and the object likes:

 @XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
private String name;
    private String surname;
public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }
}

I want to marshal it to this xml:

<root>
    <name><![CDATA[test]]></name>
    <surname>test</surname>
</root>

but now it displays as :

<root>
    <name>&lt;![CDATA[test]]&gt;</name>
    <surname>test</surname>
</root>

Could you please tell me what's wrong with it?

1

There are 1 answers

1
Eranda On

You cannot directly parse the xml which is inside CDATA because the whole purpose of adding as CDATA is to be ignored by the parser. You can get the data inside CDATA element as below and you can parse that.

SOAPBody soapBody = soapMessage.getSOAPBody();
NodeList nodeList = soapBody.getElementsByTagName("outerElementOfCDATA");
Element element = (Element) nodeList.item(0);
Node child = element.getFirstChild();
String characterData;
if (child instanceof CharacterData) {
   characterData = ((CharacterData) child).getData();
}