// Collection of code snippets by Arne VajhÃ¸j 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import org.apache.xpath.XPathAPI;

public class SelectWithXPathW3CDOMStandard {
    public static void main(String[] args) {
        try {
            // læs fra fil til DOM træ
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse("C:\\test.xml");
            XPath xpath = XPathFactory.newInstance().newXPath();
            // find element hvor no=2
            Element res1 = (Element)xpath.evaluate("/medlemmer/medlem[@no=2]", doc.getDocumentElement(), XPathConstants.NODE);
            Element name1 = (Element)res1.getElementsByTagName("navn").item(0);
            System.out.println(name1.getFirstChild().getNodeValue());
            // find alle elementer hvor no >= 2
            NodeList res2 = (NodeList)xpath.evaluate("/medlemmer/medlem[@no>=2]", doc.getDocumentElement(), XPathConstants.NODESET);
            for(int i = 0; i < res2.getLength(); i++) {
                Element name2 = (Element)((Element)res2.item(i)).getElementsByTagName("navn").item(0);
                if(name2 != null) {
                    System.out.println(name2.getFirstChild().getNodeValue());
                }
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
    }
}
