gpt4 book ai didi

java - XML 字符串到对象数组

转载 作者:行者123 更新时间:2023-12-02 07:04:21 26 4
gpt4 key购买 nike

我从网络服务收到一个 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>

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

最佳答案

如果您想在 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);

关于java - XML 字符串到对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16273871/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com