SOAPMessage如何解析<! - [CDATA []] - >?

时间:2015-06-22 01:49:21

标签: java soap cdata

以下是将java对象编组为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;
    }

并且对象喜欢:

 @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;
    }
}

我想把它编组到这个xml:

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

但现在显示为:

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

你能告诉我它有什么问题吗?

1 个答案:

答案 0 :(得分:2)

您无法直接解析CDATA内部的xml,因为解析器会忽略添加为CDATA的全部目的。您可以在CDATA元素中获取数据,如下所示,您可以解析它。

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