views:

331

answers:

1

I'm trying to access a web service with JAX-WS using:

Dispatch<Source> sourceDispatch = null;
sourceDispatch = service.createDispatch(portQName, Source.class, Service.Mode.PAYLOAD);
Source result = sourceDispatch.invoke(new StreamSource(new StringReader(req)));
System.out.println(sourceToXMLString(result));

where:

private static String sourceToXMLString(Source result) {
    String xmlResult = null;
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        //transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        OutputStream out = new ByteArrayOutputStream();
        StreamResult streamResult = new StreamResult();
        streamResult.setOutputStream(out);
        transformer.transform(result, streamResult);
        xmlResult = streamResult.getOutputStream().toString();
    } catch (TransformerException e) {
        e.printStackTrace();
    }
    return xmlResult;
}

What is the proper way to access the contents of the response, eg. get the content of a specific element in the response?

All the available examples just print the full XML response :(

+1  A: 

Try using Transformer#transform() with a DOMResult and then use the resulting Node.

private static void sourceToXML(Source result) {
    Node rootNode= null;
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        DOMResult domResult = new DOMResult();
        transformer.transform(result, domResult );
        rootNode = domResult.getNode()
    } catch (TransformerException e) {
        e.printStackTrace();
    }
    // Process rootNode here
}
Kevin