Java HTML / XML How to - Evaluate an XPath query excluding xml tag








Question

We would like to know how to evaluate an XPath query excluding xml tag.

Answer

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
//from   ww  w  . j  av  a2  s .co  m
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Main {
    public static void main(String[] args) throws Exception {
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList nodes = (NodeList) xpath.evaluate("/bookshelf/shelf/book/*", 
                new InputSource(Main.class.getResourceAsStream("/books.xml")),
                XPathConstants.NODESET);
        System.out.println("First  node: " + nodes.item(0));
        System.out.println("Second node: " + nodes.item(1));
    }
}