How do I remove a soap envelope using JDOM and return the remainder of the XML as a String?

StackOverflow https://stackoverflow.com/questions/19769120

  •  03-07-2022
  •  | 
  •  

문제

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:

  • Is there a good introduction/tutorial to JDOM 2? (The website seems to only have the JavaDocs, which makes it a bit difficult to get started...)
  • I realise using JDOM is probably a bit over the top for this one. Any suggestions on how to do this in an easier way?
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top