I would like to add a default name space to the root element of a XML document using dom4j, like in the following snippet. What is the correct way to do this with dom4j?
<?xml version="1.0" encoding="utf-8" ?>
<animals xmlns="http://zoo.domain.org/schema/animals" >
<animal id="1">
<elephant>
<name>Jumbo</name>
</elephant>
</animal>
</animals>
The dom4j API does provide the method Element#addNamespace
but the javadoc tells that the prefix may not be blank.
The following code will result in the expected namespace for animals
though:
Document document = DocumentHelper.createDocument();
Element animals = document.addElement("animals")
.addNamespace("", "http://zoo.domain.org/schema/animals");
Element animal = animals.addElement("animal")
.addAttribute("id", "1");
animal.addElement("elephant")
.addElement("name")
.addText("Jumbo");
// write document to file etc.
...
... but the child element animal
gets an empty string as default namespace, which is not what I want:
<?xml version="1.0" encoding="UTF-8"?>
<animals xmlns="http://zoo.domain.org/schema/animals">
<animal xmlns="" id="1">
<elephant>
<name>Jumbo</name>
</elephant>
</animal>
</animals>
The method Document#addElement
(but also Element#addElement
) accepts a second parameter namespaceURI
. That does the trick, adding the default namespace to the XML element.
The following code will result in the expected XML.
Document document = DocumentHelper.createDocument();
Element animals = document.addElement("animals", "http://zoo.domain.org/schema/animals");
Element animal = animals.addElement("animal")
.addAttribute("id", "1");
animal.addElement("elephant")
.addElement("name")
.addText("Jumbo");
// write document to file etc.
...
Also worth mentioning is that in case you would like to create an Element on its own DocumentFactory#createElement
has an overloaded version that accepts a namespaceURI
as well. DocumentHelper#createElement
does not have such an overloaded method.