我正在使用jax-ws并实现一个soap处理程序来修补出站请求。 我在肥皂元素和节点元素中淹没了2天。
这是我的代码:
public boolean handleMessage(SOAPMessageContext context) {
boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
try {
if (outbound) {
SOAPMessage msg = context.getMessage();
SOAPPart sp = msg.getSOAPPart();
SOAPEnvelope env = sp.getEnvelope();
SOAPBody body = env.getBody();
NodeList list = body.getElementsByTagName("template");
if(list.getLength() > 0) {
Element template = (Element) list.item(0);
if (template != null) {
String newBodyText = StringEscapeUtils.unescapeHtml(template.getTextContent());
Element bodyElement= XmlUtils.getBodyElement(newBodyText);
SOAPElement requestElement = SOAPFactory.newInstance().createElement(bodyElement);
body.removeContents();
body.insertBefore(requestElement, null);//HERE IS THE EXCEPTION
msg.saveChanges();
System.out.println("AFTER PATCHING REQUEST :");
msg.writeTo(System.out);
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
return true;
}
方法XmlUtils.getBodyElement
如下:
public static Element getBodyElement(String fromText) {
Element result = null;
String cleanSource = StringEscapeUtils.unescapeJava(fromText).replaceAll("\\r\\n", "");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document allDocument = builder.parse(new ByteArrayInputStream(cleanSource.getBytes()));
NodeList list = allDocument.getElementsByTagName("soapenv:Body");
if(list.getLength() > 0) {
Element body = (Element)list.item(0);
result = (Element)body.getFirstChild();
}
} catch(Exception e) {
e.printStackTrace();
}
return result;
}
最后,当我尝试在主体中插入新创建的SOAPElement
时,我得到以下异常:
org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it.
我的想法已经不多了。你知道我应该怎么做吗?