java - 从 XML 文档获取节点

标签 java xml api xml-parsing

我使用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>
  1. 我能以某种方式获取所有节点 <hourly>其中<tempC> > 0 和 <weatherDesc> = 下雨?

  2. 如何从响应中排除我不感兴趣的节点<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/

相关文章:

c# - 如何获取XML中带有列名的数据?

java - 使用 MOXy 时使用 IDRef 编码 XML 标签的问题

javascript - jQuery 的 .done() 和 .always() 永远不会被调用

api - Telegram API与Bot API

java - 如何使用 Spring Boot 配置文件

java - 如何在 apache POI 中读取 excel 文件的确切单元格内容

java - com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException。 WHERE 子句

c# - 删除 xml 节点 -Xelement

api - presentRequestsDialogModallyWithSession无法正常工作,但效果很好

java - 如何通过makefile从命令行向java程序传递参数