// 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 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 SelectWithXPathW3CDOMXerces {
    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");
            // find element hvor no=2
            Element res1 = (Element)XPathAPI.selectSingleNode(doc.getDocumentElement(), "/medlemmer/medlem[@no=2]");
            Element name1 = (Element)res1.getElementsByTagName("navn").item(0);
            System.out.println(name1.getFirstChild().getNodeValue());
            // find alle elementer hvor no >= 2
            NodeList res2 = XPathAPI.selectNodeList(doc.getDocumentElement(), "/medlemmer/medlem[@no>=2]");
            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 (TransformerException e) {
            e.printStackTrace();
        }
    }
}
