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>