// 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.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.traversal.DocumentTraversal;
import org.w3c.dom.traversal.NodeFilter;
import org.w3c.dom.traversal.TreeWalker;
import org.xml.sax.SAXException;

public class ScanWithWalker {
    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");
            // walk alle elementer af typen navn
            TreeWalker walk = ((DocumentTraversal) doc).createTreeWalker(doc.getDocumentElement(), NodeFilter.SHOW_ELEMENT, null, false);
            Node n;
            while ((n = walk.nextNode()) != null) {
                if (n.getNodeName().equals("navn")) {
                    System.out.println(n.getFirstChild().getNodeValue());
                }
            }
        } catch (FactoryConfigurationError e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
