Reputation: 6430
I have the following XML with a soap envelope as a Java String
:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<MyStartElement xmlns="http://www.example.com/service">
...
I want to be able to use hamcrest and the xml-matchers extension https://code.google.com/p/xml-matchers on it later on, but first I want to get rid of the soap envelope.
How can I remove the soap envelope using JDOM 2.0.5 and get the remaining XML (i.e. starting with the MyStartElement
as root) back as a String
?
I tried the following:
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(toInputStream(THE_XML));
Namespace ns = Namespace
.getNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
Namespace ns2 = Namespace
.getNamespace("http://www.example.com/service");
Element response = document.getRootElement()
.getChild("Body", ns)
.getChild("MyStartElement", ns2);
System.out.println(new XMLOutputter().outputString(new Document(response)));
This returns: Exception in thread "main" org.jdom2.IllegalAddException: The Content already has an existing parent "soap:Body"
I had a similar setup, where I called
System.out.println(new XMLOutputter().outputString(new Document(response)));
but that returned the whole XML including soap envelope.
What would I have to do to strip the soap envelope from my XML using JDOM and get a String
back?
Bonus questions:
Upvotes: 3
Views: 2959
Reputation: 17707
JDOM content can be attached to only one parent (Element/Document) at a time. Your response is already attached to the parent Element 'Body' in the soap namespace.
You either need to detach the response from it's parent, or you need to clone it and create a new instance..... In this case, detach()
is your friend:
response.detach();
System.out.println(new XMLOutputter().outputString(new Document(response)));
as the maintainder of the JDOM project it comes naturally to me to recommend that you use it, so take it with the appropriate level of bias.
As for an introduction/tutorial for JDOM, well, you're right, it's not fantastic, but, the FAQ is useful, and I set up a 'primer' on the github wiki here. If you have any questions the jdom-interest mailing list is active, and I regularly monitor the jdom
and jdom-2
tags here in stackoverflow.
Upvotes: 2