[ACCEPTED]-How to build an XML document in Java concisely?-builder
dom4j or jdom are probably the most elegant, you 3 can write code how you like it. Dom4j has 2 builders if I recall, and yes the code is 1 more verbose.
Take a look at XOM. It's fast, simple, correct, and 1 isn't verbose.
Why don't you just use JAXB anyway.. then 2 the problem becomes a very simple object 1 to object mapping and you avoid xml altogether.
While not quite as concise as builders in 13 scripting languages, StaxMate makes things quite 12 simple; generally as simple as tree models 11 structurally, but it additionally supports 10 typed addition (implicit conversions). And 9 does this all directly into a stream, meaning 8 very low memory usage (and high speed if 7 that matters).
For what it's worth, it also 6 supports fluent style (as of 2.0.x), since 5 it does often make sense. The main benefit 4 over full data binding (and tree model) solutions 3 is probably low memory usage; very little 2 state is kept around, all output goes out 1 to destination as soon as possible.
Underscore-java has a builder to create xml string from 1 object.
String xml = U.objectBuilder().add("author", U.arrayBuilder() .add(U.objectBuilder() .add("-name", "Toby") .add("-location", "Germany") .add("#text", "Tobias Rademacher")) .add(U.objectBuilder() .add("-name", "James") .add("-location", "UK") .add("#text", "James Strachan"))).toXml(); // <?xml version="1.0" encoding="UTF-8"?> // <root> // <author name="Toby" location="Germany">Tobias Rademacher</author> // <author name="James" location="UK">James Strachan</author> // </root>
You may be able to consider JIBX, you may be 13 able to define a mapping from your domain model 12 classes to your target XML schema.
Alternatively, if 11 that's not possible, although I know you 10 state that you've discounted using binding 9 technologies I'd encourage you to review 8 that decision, copying from your domain 7 model into a generated model will most likely 6 make for cleaner, more maintainable and 5 less error prone code than what you're proposing, (which 4 JIBX can also do).
I should probably add, in 3 my experience asking questions about JIBX 2 here is fruitless but their mailing list 1 is very helpful.
More Related questions