// 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.io.FileOutputStream;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class DOM4J {
    private final static String XML_FILE = "/work/employees.xml";
    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws Exception {
        // read from file to DOM tree
        SAXReader xmlReader = new SAXReader();
        Document doc = xmlReader.read(XML_FILE);
        // iterate over all employee elements
        for(Element employee : (List<Element>)doc.getRootElement().elements("employee")) {
            // find attribute no
            String no = employee.attributeValue("no");
            // find sub elements name and role
            String name = employee.elementText("name");
            String role = employee.elementText("role");
            // print
            System.out.println("no=" + no);
            System.out.println("name=" + name);
            System.out.println("role=" + role);
        }
        // add employee
        Element newemployee = doc.getRootElement().addElement("employee");
        newemployee.addAttribute("no", "4");
        newemployee.addElement("name").addText("Dave D");
        newemployee.addElement("role").addText("Intern");
        // write out
        OutputFormat of = OutputFormat.createPrettyPrint();
        FileOutputStream fos = new FileOutputStream("/work/employees2.xml");
        XMLWriter xw = new XMLWriter(fos, of);
        xw.write(doc);
        xw.close();
        fos.close();
    }
}
