title: Java xml saver optimization
body: <p>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 :</p>
  
  <pre><code>    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);
  </code></pre>