Create empty text node in DOM Document

Indigo picture Indigo · Mar 20, 2014 · Viewed 15.9k times · Source

How can we create an empty node in a DOM document without getting java.lang.NullPointerException while writing XML files with Transformer?

I am writing an XML Document with some nodes possibly with empty values using element.appendChild(documnet.createTextNode(nodeValue));

Here this nodeValue could be an empty String or lets say null or empty value, then how could we force it to write this empty text node like <emptyTextNode/> or <emptyTextNode><emptyTextNode>

If I just simply write this node with an empty value, Transformer throws NullPointerException, while transforming the Document to XML.

This nullpointer exception needs to be avoided and allow this empty node in output XML anyhow condition.

Answer

helderdarocha picture helderdarocha · Mar 20, 2014

If you are using Java SE org.w3c.dom you will only get NullPointerException if you append a null child. If you append no child or an empty text node you will get an empty element, but not a NullPointerException.

For example, suppose you create these elements in a DOM:

Element root = doc.createElement("root");

Element textNode = doc.createElement("textNode");
Element emptyTextNode = doc.createElement("emptyTextNode");
Element emptyNode = doc.createElement("emptyNode");
Element nullNode = doc.createElement("nullTextNode");

textNode.appendChild(doc.createTextNode("not empty")); // <textNode>not empty</textNode>
emptyTextNode.appendChild(doc.createTextNode(""));     // <emptyTextNode></emptyTextNode>
// emptyNode: no child appended                           <emptyNode /> 
nullNode.appendChild(null);                            // null child appended - causes NPE!!

root.appendChild(textNode);
root.appendChild(emptyTextNode);
root.appendChild(emptyNode);
root.appendChild(nullNode);

Only the nullNode causes NullPointerException. To avoid it, you should guarantee that nodeValue is not null, but it can be an empty string.

If the line that causes NPE is commented, the result will be:

<root>
  <textNode>not empty</textNode>
  <emptyTextNode/>
  <emptyNode/>
  <nullTextNode/>
</root>