I have this code
DocumentBuilderFactory docb = DocumentBuilderFactory.newInstance();
DocumentBuilder dom = docb.newDocumentBuilder();
Document doc = dom.newDocument();
Element raiz = doc.createElement("Alumnos");
//-Problem here
doc.getDocumentElement().appendChild(raiz);
This is supposed to create an XML file, but when I try to do it, I get an exception:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "org.w3c.dom.Element.appendChild(org.w3c.dom.Node)" because the return value of "org.w3c.dom.Document.getDocumentElement()" is null
I'm not sure why I get this and why the document element is null. Am I forgetting something?
I tried to create an XML file to append elements later, but I got that error.
You've created an empty document, it doesn't yet have a "documentElement", so getDocumentElement()
returns null
. The method doc.createElement
just creates an element, it doesn't add it to the document, you need to do that explicitly:
DocumentBuilderFactory docb = DocumentBuilderFactory.newInstance();
DocumentBuilder dom = docb.newDocumentBuilder();
Document doc = dom.newDocument();
Element raiz = doc.createElement("Alumnos");
doc.appendChild(raiz);
In other words, remove the call to getDocumentElement()
, but call appendChild(raiz)
directly on doc
. This will make Alumnos
the document element (root element).
Afterwards, calls to doc.getDocumentElement()
will return the same object as referenced by raiz
.