Java HTML / XML How to - Parse Xml leaf node element values using JAXB








Question

We would like to know how to parse Xml leaf node element values using JAXB.

Answer

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
/* w ww . j a v a2 s.  c om*/
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Main {

  public static void main(String[] args) throws Exception {
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xp = xpf.newXPath();

    InputSource xml = new InputSource("input.xml");
    NodeList leafNodeObjects = (NodeList) xp.evaluate("//*[not(*)]", xml,
        XPathConstants.NODESET);

    for (int x = 0; x < leafNodeObjects.getLength(); x++) {
      System.out.print("nodeElement = ");
      System.out.print(leafNodeObjects.item(x).getNodeName());
      System.out.print(" and node value = ");
      System.out.println(leafNodeObjects.item(x).getTextContent());
    }
  }

}