XML-String到对象数组

时间:2013-04-29 08:04:08

标签: java xml web-services

我收到来自网络服务的回复String,看起来像这样。

<?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>

如何获取数组标题和网址?

2 个答案:

答案 0 :(得分:2)

如果你想在XML文件中搜索某些东西,你应该使用XPath。

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

修改

 String input = "XMLAsString";
 InputStream is= new ByteArrayInputStream(input.getBytes());
 Document doc = builder.parse(is);

答案 1 :(得分:0)

您正在寻找的是XML解析器。看看这里的答案:

Best XML parser for Java