0

I'm trying to replace SOAP Body element with a string from SOAP message (SOAPMessage object) which looks like

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://www.w3.org/2005/08/addressing">
  <soap:Header>
   ..... SOAP Headers ....
    </soap:Header>
    <soap:Body>
    ... SOAP body part...
    </soap:Body>
</soap:Envelope>

to

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://www.w3.org/2005/08/addressing">
  <soap:Header>
   ..... SOAP Headers ....
    </soap:Header>
    <soap:Body>
     Body part was removed.
    </soap:Body>
</soap:Envelope>

To do that I have used XPath

Document doc = convertStringToDocument(message);
XPath xpath = XPathFactory.newInstance().newXPath();

String expression = "//soap:Envelope/soap:Body";
Node node = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);

// Set the node content
node.setTextContent("Body part was removed.");

TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
StringWriter buffer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(buffer));
String markedMessage = buffer.toString();

but it came back as node = nullso it wasn't replaced with a string

JackTheKnife
  • 3,795
  • 8
  • 57
  • 117
  • Looks like you cannot use wildcard namespaces like `*:Envelope` or `*:Body`. Try using `//soap:Envelope/soap:Body` instead with a fully declared namespace. – zx485 Mar 20 '18 at 20:23
  • Try to use local-name() isntead of * wildcard – dgebert Mar 20 '18 at 20:31
  • 1
    `//*:Envelope/*:Body` requires XPath 2.0, defeats namespace, and is not recommended anyway (nor is `local-name()`, @dgebert). See duplicate link for how to deal properly with namespaces in XPath 1.0 – kjhughes Mar 20 '18 at 20:32
  • @kjhughes I have updated my question – JackTheKnife Mar 21 '18 at 15:11
  • 1
    @JackTheKnife: Did you read the material at the duplicate link? If so, where is your call to `setNamespaceContext()` as it suggests for Java? – kjhughes Mar 21 '18 at 15:42
  • I have fixed it with setting up `factory.setNamespaceAware()` to `false` and then `expression = "/Envelope/Body"` – JackTheKnife Mar 21 '18 at 16:03
  • 1
    Ok, but beware of the problems of defeating namespaces, also listed in the duplicate link. – kjhughes Mar 21 '18 at 16:21

0 Answers0