0

I get a response from a webservice as a String which looks like this.

<?xml version="1.0" ?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body><ns2:getTitlesResponse xmlns:ns2="http://localhost:8080/wsGrabber/GrabberService">
        <return>
            <titles>sampleTitle</titles>
            <urls>http://sample.com</urls>
        </return>
    </ns2:getTitlesResponse>
    </S:Body>
</S:Envelope>

How can I get an array titles and urls?

1
  • 1
    Consume it with a SOAP parser like Axis2 - have a Google for that an look at some examples. Commented Apr 29, 2013 at 8:08

2 Answers 2

2

XPath is something you should use if you want to search for something in an XML file.

try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder builder = documentBuilderFactory
                .newDocumentBuilder();
        Document doc = builder.parse("path/to/xml/MyXML.xml");

        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xpath = xPathFactory.newXPath();

        XPathExpression expression = xpath
                .compile("//titles");

        NodeList nodes = (NodeList) expression.evaluate(doc,
                XPathConstants.NODESET);

        for (int i = 0; i < nodes.getLength(); i++) {
            //System.out.println(nodes.item(i).getNodeName());
            System.out.println(nodes.item(i).getTextContent());
        }
    } catch (Exception exception) {
        exception.printStackTrace();
    }

EDIT

 String input = "XMLAsString";
 InputStream is= new ByteArrayInputStream(input.getBytes());
 Document doc = builder.parse(is);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your quick reply. But your example needs a xml-file. I only have a string and I don't want to save it as a xml-file.
0

What you are looking for is an XML parser. Take a look at the answers here:

Best XML parser for Java

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.