// Collection of code snippets by Arne VajhÃ¸j 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.io.File;
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.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ParseW3CDOM {
   private final static String XML_FILE = "C:\\test.xml";
   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(new File(XML_FILE));
         // lav liste over alle elementer af typen 'medlem'
         NodeList elements = doc.getElementsByTagName("medlem");
         for (int i = 0; i < elements.getLength(); i++) {
            Node element = (Element) elements.item(i);
            // find attributten no
            String no = ((Element) element).getAttribute("no");
            String name = "";
            String address = "";
            // lav liste over alle childs og find navn og adresse
            NodeList subelements = element.getChildNodes();
            for (int j = 0; j < subelements.getLength(); j++) {
               String tag = subelements.item(j).getNodeName();
               if (tag.equals("navn")) {
                  name = subelements.item(j).getFirstChild().getNodeValue();
               }
               if (tag.equals("adresse")) {
                  address = subelements.item(j).getFirstChild().getNodeValue();
               }
            }
            System.out.println("no=" + no);
            System.out.println("navn=" + name);
            System.out.println("adresse=" + address);
         }
      } catch (FactoryConfigurationError e) {
         e.printStackTrace();
      } catch (ParserConfigurationException e) {
         e.printStackTrace();
      } catch (SAXException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
      return;
   }
}
