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

大城市里の小女人 提交于 2019-12-12 05:57:12

问题


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:


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();
}


来源:https://stackoverflow.com/questions/30971116/how-can-soapmessage-parse-cdata

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!