我使用worldweatheronline API。该服务提供以下形式的xml:
<hourly>
<tempC>-3</tempC>
<weatherDesc>rain</weatherDesc>
<precipMM>0.0</precipMM>
</hourly>
<hourly>
<tempC>5</tempC>
<weatherDesc>no</weatherDesc>
<precipMM>0.1</precipMM>
</hourly>
我能以某种方式获取所有节点
<hourly>
其中<tempC>
> 0 和<weatherDesc>
= 下雨?如何从响应中排除我不感兴趣的节点
<hourly>
?
最佳答案
使用XPath这是非常可行的.
您可以根据元素值、属性值和其他条件过滤文档。
这是一个根据问题中的第一点获取元素的工作示例:
try (InputStream is = Files.newInputStream(Paths.get("C:/temp/test.xml"))) {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document xmlDocument = builder.parse(is);
XPath xPath = XPathFactory.newInstance().newXPath();
// get hourly elements that have tempC child element with value > 0 and weatherDesc child element with value = "rain"
String expression = "//hourly[tempC>0 and weatherDesc=\"rain\"]";
NodeList hours = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < hours.getLength(); i++) {
System.out.println(hours.item(i) + " " + hours.item(i).getTextContent());
}
} catch (Exception e) {
e.printStackTrace();
}
关于java - 从 XML 文档获取节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54513286/