What is the most efficient way to create XML documents from Java objects and vice versa?

Nicola Ken Barozzi

There is not AN afficient way, it depends on different parameters, because efficiency is not only how fast you parse but also how easily you do it.
Here are some examples and guidelines.

  • Parsing a big XML file: you should use the SAX API, which is event driven; this means that the document is not duplicated in memory and the parsing is fast, but is limiting beacuse you cannot go back and forth on the tree or add or subtract branches (input only);
  • Parsing a small XML file: the DOM API is much easier to use (remember to include the DTD so that unmeaningfull white spaces do not interfere with parsing), and the memory usage is small; you gain also in flexibility, because you can go back and forth on the tree, add or subtract branches and output the tree (not part of the DOM standard API but usually present in implementations);
  • Writing XML files with basically the same structure: just output the tags as String like
  • Writing XML files with variable structure: use the DOM API , which represent the XML as a tree; it is easy to bind a DOM tree to a JTree component, the code that does it is in the Jva XML Tutorial on the Javasoft site.

Now Sun is writing a binding specifications to tie the XML to Java classes (JSR-000031 XML Data Binding Specification), but at the time of the writing it isn't ready. Detailed info on the use of it is at White Papers about XML Technology .