How to unmarshall SOAP response using JAXB if namespace declaration is on SOAP envelope?

后端 未结 2 1398
既然无缘
既然无缘 2020-12-13 20:14

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

2条回答
  •  佛祖请我去吃肉
    2020-12-13 20:52

    You could parse the whole SOAP message using a DOM parser, which would be able to resolve all the namespaces at parse time. Then extract the element you require from the resulting DOM tree and pass that to the unmarshaller.

    DomDemo

    package forum11465653;
    
    import java.io.File;
    import javax.xml.bind.*;
    import javax.xml.parsers.*;
    import javax.xml.transform.dom.DOMSource;
    import org.w3c.dom.*;
    
    public class DomDemo {
    
        public static void main(String[] args) throws Exception{
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document d = db.parse(new File("src/forum11465653/input.xml"));
            Node getNumberResponseElt = d.getElementsByTagNameNS("http://example.com/", "getNumberResponse").item(0);
    
            JAXBContext jc = JAXBContext.newInstance(Response.class);
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            JAXBElement je = unmarshaller.unmarshal(new DOMSource(getNumberResponseElt), Response.class);
            System.out.println(je.getName());
            System.out.println(je.getValue());
        }
    
    }
    

    Output

    {http://example.com/}getNumberResponse
    forum11465653.Response@19632847
    

提交回复
热议问题