java - 从 XML 文档中获取节点
问题描述
我使用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>
我能以某种方式获得 > 0 和 = 下雨的所有
<hourly>
节点<tempC>
吗<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 - 如何上传和解析csv文件
- java - 如何将二维数组列表传递给接受二维列表的函数
- python - Python 多处理是否从父级复制所有模块?
- vue.js - 如何在 vuex 商店中访问 vue-cookies?
- genexus - 有一种方法可以在genexus 的New/EndNew 中查看错误消息?
- java - 如何收集字符串[][]?
- javascript - 如何在JSON的基础上在JS中添加一个类?
- hibernate - VARCHAR2(32767 CHAR) 的 Hibernate/JPA 问题:ORA-01461:只能绑定 LONG 值以插入 LONG 列
- javascript - 赛普拉斯 - 如何从网站注销
- android - 以错误的方式截断链接