I use a velocity template to create a soap request. I use the jax-ws framework to implement a web service client. I have wired a SOAP Handler to intercept outbound messages.
I am trying to replace the body content by a new body computed.
I use the following code in my handler:
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();
body.normalize();
System.out.println(body.getValue());
NodeList list = body.getElementsByTagName("template");
if(list.getLength() > 0) {
Element template = (Element) list.item(0);
if (template != null) {
String newBody = StringEscapeUtils.unescapeHtml(template.getTextContent());
Document bodyElement = XmlUtils.getDocumentFromText(newBody);
body.removeContents();
body.addDocument(bodyElement);
When I execute it, I get the following error:
org.w3c.dom.DOMException: NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
How can I change the body content from in an xml text without too much hassle?
Ok, I dig way more and it turns out I found the solution. Here is the code:
SOAPMessage msg = context.getMessage();
SOAPPart sp = msg.getSOAPPart();
SOAPEnvelope env = sp.getEnvelope();
SOAPBody body = env.getBody();
body.normalize();
System.out.println(body.getValue());
NodeList list = body.getElementsByTagName("template");
if(list.getLength() > 0) {
Element template = (Element) list.item(0);
if (template != null) {
String newBody = StringEscapeUtils.unescapeHtml(template.getTextContent());
Document bodyElement = XmlUtils.getBody(newBody);
body.removeContents();
body.addDocument(bodyElement);
More important, the method XmlUtils.getBody:
public static Document getBody(String fromText) {
Document result = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
result = builder.parse(new ByteArrayInputStream(fromText.getBytes()));
NodeList list = result.getElementsByTagNameNS("soapenv", "Body");
if(list.getLength() > 0) {
Node body = list.item(0);
result = builder.newDocument();
result.adoptNode(body);
}
} catch(Exception e) {
e.printStackTrace();
}
return result;
}
I was actually the factory.setNamespaceAware(true)
part in my previous code, explaining the exception raised back then.
Problem solved!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.