Creating a new Document instance from scratch

This lecture's exercises are based on Jdom in favour of a real Java DOM language binding implementation.

Figure 710. Prerequisite: pom.xml configuration Slide presentation Create comment in forum

The following recipe allows for wrapping data (e.g. from a RDBMS) into XML:

Figure 711. Exporting data as XML Slide presentation Create comment in forum

Create an empty Element instance to become the document's root.

Add a Text node.

Set a new attribute date to value 23.02.2000.

Create a serializer instance of XMLOutputter providing output prettifying.

Serialize the result tree to a stream.

The subsequent code illustrates these steps:

Figure 712. XML document creation from scratch. Slide presentation Create comment in forum
final Element titel = new Element("titel"); 

titel.addContent(new Text("First try")); 

titel.setAttribute("date", "23.02.2000"); 

final XMLOutputter printer =
      new XMLOutputter(Format.getPrettyFormat());

printer.output(titel, System.out); 
Result: <titel  date="23.02.2000">First try</titel>