I am using DOM parser in Java to add child nodes into existing nodes.
My XML is
edit: To the original Question: Yes the appendChild thing works the way you planed, the problem lies within getElementById.
The NullPointerException means there was no Element with that ID. The javadoc gives it away:
http://docs.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Document.html#getElementById(java.lang.String)
The DOM implementation is expected to use the attribute Attr.isId to determine if an attribute is of type ID.
and further in the Documentation of Attr:
http://docs.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Attr.html#isId()
So basically you need either a DTD or a schema for your document and need to set
DocumentBuilderFactory.setValidating(true)
or set the IsId property by hand.
personally i used: (dirty&scala for lazyness)
import org.w3c.dom.{Document,Node,Attr,Element}
def idify ( n:Node ) {
if ( n.getNodeType() == Node.ELEMENT_NODE ){
val e = n.asInstanceOf[Element ]
if (e.hasAttributeNS(null , "id" ) )e.setIdAttributeNS(null , "id" , true )
}
val ndlist = n.getChildNodes()
for ( i <- 0 until ndlist.getLength ) idify(ndlist.item(i) )
}
There surely are more professional ways to do this that do not involve drafting up a complete DTD/schema. If someone knows, i'm curious as well.
getElementById
is specifically for retrieving DOM elements by their id
attribute. Try this instead:
this.widgetDoc.getElementById("legendNode").appendChild(myNode);
For other ways of retrieving DOM nodes, look into querySelector and querySelectorAll.