Fastest and most efficient way to create XML

If I was to create a very simple XML content, I would stick to the JDK api only, introducing no third party dependencies.

So for simple XML and if I was to map XML file to Java classes (or vice-versa), I would go for JAXB. See this tutorial to see how easy it is.

Now.

If I was to create some more sophisticated XML output with constant scheme, I would use some templating engine, Freemarker perhaps. Thymeleaf looks nice as well.

And finally.

If I was to create huge XML files very effectively, I would use SAX parser.

I hope you understand now, that you have plenty of possibilities - choose the best match for your needs :)

And have fun!


Try Xembly, a small open source library that makes this XML creating process very easy and intuitive:

String xml = new Xembler(
  new Directives()
    .add("root")
    .add("order")
    .attr("id", "553")
    .set("$140.00")
).xml();

Xembly is a wrapper around native Java DOM, and is a very lightweight library (I'm a developer).


Firstly, it's important that the serialization is correct. Hand-written serializers usually aren't. For example, they have a tendency to forget that the string "]]>" can't appear in a text node.

It's not too difficult to write your own serializer that is both correct and fast, if you're a capable Java programmer, but since some very capable Java programmers have been here before I think you're unlikely to beat them by a sufficient margin to make it worth the effort of writing your own code.

Except perhaps that most general-purpose libraries might be slowed down a little by offering serialization options - like indenting, or encoding, or like choosing your line endings. You might just squeeze an extra ounce of performance by avoiding unwanted features.

Also, some general-purpose libraries might check the well-formedness of what you throw at them, for example checking that namespace prefixes are declared (or declaring them if not). You might make it faster if it does no checking. On the other hand, you might create a library that is fast, but a pig to work with. Putting performance above all other objectives is almost invariably a mistake.

As for the performance of available libraries, measure them, and tell us what you find out.