Reputation: 181
I'm trying to remove the soap envelope in an xml message and just keeping the body, but instead, I've ended up remove everything besides whatever is above the parent node.
This is the xml message:
<soap:Envelope xmlns:soap="test" xmlns:ns="test">
<soap:Header/>
<soap:Body>
<book>
<person>
<name>Person 1</name>
</person>
<person>
<name>Person 2</name>
</person>
<person>
<name>Person 3</name>
</person>
<person>
<name>Person 4</name>
</person>
</book>
</soap:Body>
</soap:Envelope>
I want to remove the soap envelopes so ultimately, I should end up with the following xml message:
<book>
<person>
<name>Person 1</name>
</person>
<person>
<name>Person 2</name>
</person>
<person>
<name>Person 3</name>
</person>
<person>
<name>Person 4</name>
</person>
</book>
This is my method code:
public static void deleteNodeFromXML(String xmlString, String elementName, String propertyName) {
String value = null;
try {
NodeList nodeList = getNodeListFromXML(xmlString, elementName);
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("NODE CONDITION MET");
Element element = (Element) node;
element.getParentNode().removeChild(element);
System.out.println("ABOUT TO PRINT OUT THE NEW XML: " );
printXML(doc);
The way I seem to be doing it isnt working.
Upvotes: 1
Views: 5952
Reputation: 5251
I'm using the following (plain Java):
String xmlWithoutSoapEnveloppe = xmlWithSoapEnveloppe.replaceAll("\\s*<\\/?(?:SOAP-ENV|soap):(?:.|\\s)*?>", "");
Upvotes: 0
Reputation: 325
SimpleXml can do it:
final String yoursoap = ...;
final SimpleXml simple = new SimpleXml();
System.out.println(simple.domToXml(getBook(simple.fromXml(yoursoap))));
private static Element getBook(final Element element) {
return element.children.get(1).children.get(0);
}
Will output:
<book><person><name>Person 1</name></person><person><name>Person 2</name></person><person><name>Person 3</name></person><person><name>Person 4</name></person></book>
From maven central:
<dependency>
<groupId>com.github.codemonstur</groupId>
<artifactId>simplexml</artifactId>
<version>1.4.0</version>
</dependency>
Upvotes: 1