0

我从 web 服务中得到响应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>

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

4

2 回答 2

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);
于 2013-04-29T08:11:55.610 回答
0

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

Java 的最佳 XML 解析器

于 2013-04-29T08:10:24.177 回答