简体   繁体   English

从XML文档获取节点

[英]Getting a node from an XML document

I use the worldweatheronline API. 我使用worldweatheronline API。 The service gives xml in the following form: 该服务以以下形式提供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. Can I somehow get all the nodes <hourly> in which <tempC> > 0 and <weatherDesc> = rain? 我能以某种方式让所有的节点<hourly><tempC> > 0和<weatherDesc> =雨?

  2. How to exclude from the response the nodes that are not interesting to me <hourly> ? 如何从响应中排除对我<hourly>不感兴趣的节点?

This is quite feasible using XPath . 使用XPath完全可行。
You can filter a document based on element values, attribute values and other criteria. 您可以根据元素值,属性值和其他条件过滤文档。 Here is a working example that gets the elements according to the first point in the question: 这是一个根据示例中的第一点获取元素的工作示例:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM