// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package xmlproc;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class W3CDOM_XPath {
    private final static String XML_FILE = "/work/employees.xml";
    public static void main(String[] args) throws Exception {
        // read from file to DOM tree
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new File(XML_FILE));
        // setup XPath
        XPath xpath = XPathFactory.newInstance().newXPath();
        // iterate over all employee elements
        NodeList employees = (NodeList)xpath.evaluate("//employee[@no>1 and role!='Intern']", doc.getDocumentElement(), XPathConstants.NODESET);
        for (int i = 0; i < employees.getLength(); i++) {
            Element employee = (Element)employees.item(i);
            // find attribute no
            String no = (String)xpath.evaluate("@no", employee, XPathConstants.STRING);
            // find sub elements name and role 
            String name = (String)xpath.evaluate("name/text()", employee, XPathConstants.STRING);
            String role = (String)xpath.evaluate("role/text()", employee, XPathConstants.STRING);
            // print
            System.out.println("no=" + no);
            System.out.println("name=" + name);
            System.out.println("role=" + role);
        }
    }
}
