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

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class JDOM {
    private final static String XML_FILE = "/work/employees.xml";
    public static void main(String[] args) throws Exception {
        // read from file to DOM tree
        SAXBuilder b = new SAXBuilder();
        Document doc = b.build(XML_FILE);
        // iterate over all employee elements
        List<?> list = doc.getRootElement().getChildren();
        for (int i = 0; i < list.size(); i++) {
            Element employee = (Element)list.get(i);
            // find attribute no
            String no = employee.getAttributeValue("no");
            // find sub elements name and role
            String name = employee.getChild("name").getText();
            String role = employee.getChild("role").getText();
            // print
            System.out.println("no=" + no);
            System.out.println("name=" + name);
            System.out.println("role=" + role);
        }
        // add employee
        Element newname = new Element("name");
        newname.setText("Dave D");
        Element newrole = new Element("role");
        newrole.setText("Intern");
        Element newemployee = new Element("employee");
        newemployee.setAttribute("no", "4");
        newemployee.addContent(newname);
        newemployee.addContent(newrole);
        doc.getRootElement().addContent(newemployee);
        // write out
        XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
        Writer w = new FileWriter("/work/employees2.xml");
        w.write(fmt.outputString(doc));
        w.close();
    }
}
