// 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.util.List;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Text;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

public class JDOM_XPath {
    private final static String XML_FILE = "/work/employees.xml";
    public static void main(String[] args) throws Exception {
        // read from file to DOM tree
        SAXBuilder b = new SAXBuilder();
        Document doc = b.build(XML_FILE);
        // iterate over all employee elements
        List<?> list = XPath.selectNodes(doc.getRootElement(), "//employee[@no>1 and role!='Intern']");
        for (int i = 0; i < list.size(); i++) {
            Element employee = (Element)list.get(i);
            // find attribute no
            String no = ((Attribute)XPath.selectSingleNode(employee, "@no")).getValue();
            // find sub elements name and role
            String name = ((Text)XPath.selectSingleNode(employee, "name/text()")).getText();
            String role = ((Text)XPath.selectSingleNode(employee, "role/text()")).getText();
            // print
            System.out.println("no=" + no);
            System.out.println("name=" + name);
            System.out.println("role=" + role);
        }
    }
}
