Java HTML / XML How to - Count a certain tag by name with XPath








Question

We would like to know how to count a certain tag by name with XPath.

Answer

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
/*  w ww  .  jav a  2  s.com*/
import org.xml.sax.InputSource;

public class Main {

  public static void main(String[] args) throws Exception {
    InputSource inputSource = new InputSource("input.xml");
    XPath xPath = XPathFactory.newInstance().newXPath();
    String text = xPath.evaluate("/note/body", inputSource);
    System.out.println(text);
  }

}