java—从xml文档获取节点

6yt4nkrj  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(328)

我使用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> ?

qyzbxkaa

qyzbxkaa1#

我认为您应该从xml创建xsd并生成jaxb类,使用这些jaxb类您可以轻松地解组xml并处理您的逻辑。

bnl4lu3b

bnl4lu3b2#

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

相关问题