// 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.io.OutputStream;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;

public class WriteStAX {
    public static void main(String[] args) throws Exception {
        // create employees
        Employees employees = new Employees();
        employees.getList().add(new Employee(1, "Alan A", "Manager"));
        employees.getList().add(new Employee(2, "Brian B", "Engineer"));
        employees.getList().add(new Employee(3, "Chris C", "Sales rep"));
        employees.getList().add(new Employee(4, "Dave D", "Intern"));
        // write out
        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        OutputStream os = new FileOutputStream("/work/employees2.xml");
        XMLStreamWriter xsw = xof.createXMLStreamWriter(os);
        xsw.writeStartDocument();
        xsw.writeStartElement("employees");
        for(Employee employee : employees.getList()) {
            xsw.writeStartElement("employee");
            xsw.writeAttribute("no", Integer.toString(employee.getNo()));
            xsw.writeStartElement("name");
            xsw.writeCharacters(employee.getName());
            xsw.writeEndElement();
            xsw.writeStartElement("role");
            xsw.writeCharacters(employee.getRole());
            xsw.writeEndElement();
            xsw.writeEndElement();
        }
        xsw.writeEndElement();
        xsw.writeEndDocument();
        xsw.close();
        os.close();
    }
}
