How to retrieve node after node of XML tree using Xpath?

后端 未结 1 1056
無奈伤痛
無奈伤痛 2021-01-06 18:17

First, I must say that I find Xpath as a very nice parser , and I guess pretty powerful when comparing it to other parsers .

Given the following code :<

相关标签:
1条回答
  • 2021-01-06 19:03

    Option 1 - Iterate over all Value elements in the document. Only one evaluation required, but difficult to know which Round or Door element the Value belongs to.

    NodeList result = (NodeList) xpath.evaluate("//Round/Door/Value/*/text()", doc, XPathConstants.NODESET);
    

    Option 2 - Iterate over each Round, Door and Value elements separately. Requires more evaluations but the context is easily known. If index is required, it is easy to add a counter to the loops.

    // Get all rounds and iterate over them
    NodeList rounds = (NodeList) xpath.evaluate("//Round", doc, XPathConstants.NODESET);
    for (Node round : rounds) {
      // Get all doors and iterate over them
      NodeList doors = (NodeList) xpath.evaluate("Door", round, XPathConstants.NODESET);
      for (Node door : doors) {
        // Get all values and iterate over them
        NodeList values = (NodeList) xpath.evaluate("Value/*/text()", door, XPathConstants.NODESET);
        for (Node value : values) {
          // Do something
        }
      }
    }
    

    Option 3 - Do some combination of the above depending on your requirements

    Note that I've removed the expression compilation step to shorten the example. It should be re-added to improve performance.

    0 讨论(0)
提交回复
热议问题