MRM
MRM

Reputation: 569

Java xml saver optimization

I have a colection of objects organised in trees that i want to save as a XML file, but i want to do this as optimally as i can. I use somehing like this (see the code) to do it, but i would appeciate if someone could tell me a better way of doing it :

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();


    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("company");
    doc.appendChild(rootElement);


    Element staff = doc.createElement("Staff");
    rootElement.appendChild(staff);


    Attr attr = doc.createAttribute("id");
    attr.setValue("1");
    staff.setAttributeNode(attr);


    Element firstname = doc.createElement("firstname");
    firstname.appendChild(doc.createTextNode("yong"));
    staff.appendChild(firstname);


    Element lastname = doc.createElement("lastname");
    lastname.appendChild(doc.createTextNode("mook kim"));
    staff.appendChild(lastname);


    Element nickname = doc.createElement("nickname");
    nickname.appendChild(doc.createTextNode("mkyong"));
    staff.appendChild(nickname);


    Element salary = doc.createElement("salary");
    salary.appendChild(doc.createTextNode("100000"));
    staff.appendChild(salary);


    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File("C:\\file.xml"));


    transformer.transform(source, result);

Upvotes: 1

Views: 242

Answers (1)

korifey
korifey

Reputation: 3519

The shot answer is: use JAXB

In case of using it, you can put annotation such as @XmlElement on your fields and classes to serialize/deserialize them to XML seamlessly. And it will handle all the recursion in your tree without any problems.

Upvotes: 3

Related Questions