Although I know how to build a DOM the long, arduous way using the DOM API, I’d like to do something a bit better than that. Is there a nice, tidy way to build hierarchical documents with, say, an API that works something like Hibernate’s Criteria API? So that I can chain calls together like this, for example:
Document doc = createDocumentSomehow (); doc.createElement ('root').createElements ( doc.newElement ('subnode') .createElement ('sub-subnode') .setText('some element text') .addAttribute ('attr-name','attr-value'), doc.newElement ('other_subnode'));
Ideally, this would result in XML like this:
<root> <subnode> <sub-subnode attr-name = 'attr-value'>some element text</sub-subnode> <other_subnode /> </root>
Basically, I’d like something where the Java itself isn’t nearly four times longer than the document I’m generating. Does it exist?
You definitely want to use
JDom: http://www.jdom.org/docs/apidocs/ . It can be used as you described as many methods return a reference tothis. Here is some code our teacher showed us for this XML document. Haven’t tested it, but the teacher is great i believe in him:Code:
From the API manual, it looks like the casts he did aren’t necassary. Maybe he just did it for documentation purposes.