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?
Create an new Document, using newDocument() API method of DocumentBuilder. Create the root element node of the Document, using createElement(String tagName) API method of Document, with the given tagname set to "root" and append it in the Document with appendChild(Node newChild) API method of Document.
Package org. w3c. dom Description. Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing. The Document Object Model Level 2 Core API allows programs to dynamically access and update the content and structure of documents.
The Document Object Model (DOM) is an application programming interface (API) for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.
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 to this
. 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:
<adressbuch aktualisiert="1.4.2008">
<adresse>
<vorname> Hugo </vorname>
<nachname> Meier </nachname>
<telefon typ="mobil">0160/987654 </telefon>
</adresse>
</adressbuch>
Code:
new Document(
new Element ("adressbuch")
.setAttribute("aktualisiert", "1.4.2008")
.addContent(
(Element) new Element("adresse")
.addContent(
(Element) new Element("vorname")
.addContent("Hugo"))
.addContent(
(Element) new Element("nachname")
.addContent("Meier"))
.addContent(
(Element) new Element("telefon")
.setAttribute("typ", "mobil")
.addContent("0160/987654"))));
From the API manual, it looks like the casts he did aren't necassary. Maybe he just did it for documentation purposes.
I highly recommend Elliotte Rusty Harold's XOM API.
It inter-operates with the W3C API, in that you can convert between XOM and DOM. The API guarantees a well-formed structure at all times. It's performant, robust, and follows consistent design principles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With