haisi
haisi

Reputation: 1075

XML-String to object array

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?

Upvotes: 0

Views: 116

Answers (2)

Eugene
Eugene

Reputation: 120858

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);

Upvotes: 2

Yan Foto
Yan Foto

Reputation: 11378

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

Best XML parser for Java

Upvotes: 0

Related Questions