Java DOM getElementByID

Anup Singh picture Anup Singh · Apr 18, 2012 · Viewed 24.7k times · Source

I am using DOM parser in Java to add child nodes into existing nodes.

My XML is

<?xml version="1.0" encoding="iso-8859-1"?>
 <chart> 
<chart renderTo="pieContainer" defaultSeriesType="pie" zoomType="xy" plotBackgroundColor="null" plotBorderWidth="null"  plotShadow="false"></chart>
<legend id="legendNode">
  <align>center</align>
  <backgroundColor>null</backgroundColor>
  <borderColor>#909090</borderColor> 
  <borderRadius>25</borderRadius>
</legend>
 </chart>

Is there any way to directly add child nodes under existing ones? Can I use something like this?

Node myNode = nodesTheme.item(0);
this.widgetDoc.getElementById("/chart/legend").appendChild(myNode);

My Code

import org.w3c.dom.*;
import javax.xml.parsers.*;
public class TestGetElementById {
    public static void main(String[] args) throws Exception {

        String widgetXMLFile = "piechart.xml";
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();

        domFactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = domFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(widgetXMLFile);
        Node n = doc.getElementById("/chart/legend");
        //Node n = doc.getElementById("legendTag");

        Element newNode = doc.createElement("root");
        n.appendChild(newNode);
    }
}

Answer

tcmon picture tcmon · Aug 8, 2013

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.