Java HTML / XML How to - Get XML nodes from certain tree level








Question

We would like to know how to get XML nodes from certain tree level.

Answer

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
/*from  ww w  . ja  v a  2s. c o m*/
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Main {
  
  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(true);
    DocumentBuilder builder = docFactory.newDocumentBuilder();
    Document doc = builder.parse("data.xml");
    XPathExpression expr = XPathFactory.newInstance().newXPath().compile("/script/data");
    Object hits = expr.evaluate(doc, XPathConstants.NODESET);
    if (hits instanceof NodeList) {
      NodeList list = (NodeList) hits;
      for (int i = 0; i < list.getLength(); i++) {
        System.out.println(list.item(i).getTextContent());
      }
    }
  }
}

Here is the content of data.xml

<script>
  <hide>
    <data>1</data>      <!-- Ingore THIS-->
  </hide>
  <data>Find this</data><!-- FIND THIS-->
  <data>More of this</data><!-- FIND THIS-->
</script>

It yields

Find this
More of this