Extracting JAXB entities from inside SOAP wrappers can be done without string-chopping using standard APIs.
Example: using standard API.
String example = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><soapenv:Header /><soapenv:Body><ns2:farm xmlns:ns2=\"http://adamish.com/example/farm\"><horse height=\"123\" name=\"glue factory\"/></ns2:farm></soapenv:Body></soapenv:Envelope>"; SOAPMessage message = MessageFactory.newInstance().createMessage(null, new ByteArrayInputStream(example.getBytes())); Unmarshaller unmarshaller = JAXBContext.newInstance(Farm.class).createUnmarshaller(); Farm farm = (Farm)unmarshaller.unmarshal(message.getSOAPBody().extractContentAsDocument());
Anti-example seen in the wild: string chopping / regex
String example = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><soapenv:Header /><soapenv:Body><ns2:farm xmlns:ns2=\"http://adamish.com/example/farm\"><horse height=\"123\" name=\"glue factory\"/></ns2:farm></soapenv:Body></soapenv:Envelope>"; int start = example.indexOf("Body>") + 5; Matcher m = Pattern.compile("</[^>]*Body").matcher(example); m.find(); int end = m.start(); String output = example.substring(start, end); Unmarshaller unmarshaller = JAXBContext.newInstance(Farm.class).createUnmarshaller(); Farm farm = (Farm) unmarshaller.unmarshal(new ByteArrayInputStream(output.getBytes()));
Adam, I got the link to this page from your answer to the stackoverflow question http://stackoverflow.com/questions/26097760/how-to-unmarshall-soap-xml-to-java-object
When I run your sample code I got “SOAPException: Error creating Message. mimeHeaders cannot be null.” so I changed the SOAPMessage instantiation to:
SOAPMessage message = MessageFactory.newInstance().createMessage(new MimeHeaders(),
new ByteArrayInputStream(xmlString.getBytes()));
Now I get:
javax.xml.bind.UnmarshalException: unexpected element (uri:”http://adamish.com/example/farm”, local:”farm”). Expected elements are (none)
I am using Java 1.6 and trying to get my own SOAP response working with JAXB and facing other problems, but I thought if I could get a simple example working I could try to narrow down the differences between my non-working code and the working example.
Thanks for any help…
Adam, please disregard my previous post, I’ve taken a different approach using the StaxParser and got it working. Thanks. -Ken