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?

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
haisi
  • 1,035
  • 1
  • 10
  • 30
  • 1
    Consume it with a SOAP parser like Axis2 - have a Google for that an look at some examples. – David Apr 29 '13 at 08:08

2 Answers2

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);
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • 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. – haisi Apr 29 '13 at 08:41
0

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

Best XML parser for Java

Community
  • 1
  • 1
Yan Foto
  • 10,850
  • 6
  • 57
  • 88