JAXB can only unmarshall an XML if the soap envelope has already been removed. However, the SOAP response I’m trying to unmarshall has its namespace declaration on the soap envelope. If I remove the soap envelope, the namespace declaration will also be removed. As such the prefix of the tags will be referring to none. This causes JAXB to throw an error. How can I unmarshall a SOAP response using JAXB if the namespace is declared on the SOAP envelope?
A similar sample of the XML that I need to unmarshall is below:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://example.com/">
<soapenv:Body>
<ns:getNumberResponse>
<number>123456789</number>
</ns:getNumberResponse>
</soapenv:Body>
</soapenv:Envelope>
This is what happens if I remove the soap envelope:
<ns:getNumberResponse>
<number>123456789</number>
</ns:getNumberResponse>
If I removed the soap envelope, the namespace declaration will also be gone. JAXB won’t be able to unmarshall the above xml because the namespace definition for the prefix “ns” is missing. As such it will return a "The prefix "ns" for element "ns:getNumberResponse" is not bound." error message. How do I fix it?
Please note that I’m using JDK 1.5. I’m not sure if there is a way to solve this in JDK 1.6. I was able to use JAXB because I downloaded the required jars for using JAXB.
You can use a StAX parser to parse the SOAP message and then advance the
XMLStreamReaderto thegetNumberResponseelement and use the unmarshal method that takes a class parameter. A StAX parser is included in Java SE 6, but you will need to download one for Java SE 5. Woodstox is a popular StAX parser.Response
Demo
An
XMLStreamReaderhas aNamespaceContext. TheNamespaceContextknows all the active namespace declarations for the current level. Your JAXB (JSR-222) implementation will be able to leverage this to get the necessary information.Output