从 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>


largeQ
浏览 89回答 2
2回答

慕尼黑8549860

使用XPath是非常可行的。您可以根据元素值、属性值和其他条件过滤文档。这是一个根据问题的第一点获取元素的工作示例:&nbsp; &nbsp; try (InputStream is = Files.newInputStream(Paths.get("C:/temp/test.xml"))) {&nbsp; &nbsp; &nbsp; &nbsp; DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();&nbsp; &nbsp; &nbsp; &nbsp; Document xmlDocument = builder.parse(is);&nbsp; &nbsp; &nbsp; &nbsp; XPath xPath = XPathFactory.newInstance().newXPath();&nbsp; &nbsp; &nbsp; &nbsp; // get hourly elements that have tempC child element with value > 0 and weatherDesc child element with value = "rain"&nbsp; &nbsp; &nbsp; &nbsp; String expression = "//hourly[tempC>0 and weatherDesc=\"rain\"]";&nbsp; &nbsp; &nbsp; &nbsp; NodeList hours = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < hours.getLength(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(hours.item(i) + " " + hours.item(i).getTextContent());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; }

翻翻过去那场雪

我认为您应该从 xml 创建 xsd 并生成 JAXB 类。使用这些 JAXB 类,您可以轻松地解组 xml 并处理您的逻辑。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java