首页 > 解决方案 > 从 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>
  1. 我能以某种方式获得 > 0 和 = 下雨的所有<hourly>节点<tempC><weatherDesc>

  2. 如何从响应中排除我不感兴趣的节点<hourly>

标签: javaxmlapixml-parsing

解决方案


使用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();
    }

推荐阅读