Question

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.

Was it helpful?

Solution

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>

OTHER TIPS

Well, I found my mistake here,

I am using element.appendChild(documnet.createTextNode(nodeValue)); to write the empty or null value to node. Which is not correct.

I should simply just create the Element and leave it like this without attempting to write null as TextNode value. Since empty or null can never be a TextNode.

So, I have to be extra careful in my code and avoid trying to write null values. In other words, check the value first, if it's not null then only write as TextNode otherwise simply write the Element and leave it to be interpreted by the serializer while transforming.

Element childElem = document.createElement("Child");
rootElement.appendChild(childElem);

Now if some String is not null then only,

childElem.appendChild(document.createTextNode(someString));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top