Howardism Musings from my Awakening Dementia
My collected thoughts flamed by hubris
Home PageSend Comment

Eclipse Detail Formatter

While debugging some code that traversed a DOM tree in my Java code, I noticed that the variable output wasn't very helpful. It defaults to calling the variable object's toString() method, which as we all know, is not always overridden in helpful ways.

To overcome this deficiency, Eclipse has a feature called "Detail Formatter" where for each class that you are debugging, you can specify how it should display. And since it executes that code snippet as if it was part of the class definition, you don't have to worry about public vs. protected vs. private declarations. Illustration of Eclipse's Detail Formatter output

According to this nice overview, it is simple to enter the private variable or method that should be called in order to display when a variable of that particular class is displayed.

However, when traversing a DOM, I wanted a bit more information about each element I was visiting. Sure I could put either getNodeName() or getNodeValue(), but I wanted both.

You can. You simply put something like this in the dialog box:

    return getNodeName() + " - " + getNodeValue();

The results are displayed as in the cut out picture on the right. Fab.


Here is the "Detail Formatter" that I use for org.w3c.dom.Document (this works for a org.w3c.dom.Node as well) in order to display an entire XML document:

if (this == null) return null;

javax.xml.transform.TransformerFactory tf = javax.xml.transform.TransformerFactory.newInstance(); 
javax.xml.transform.Transformer transformer = tf.newTransformer();
transformer.setOutputProperty( javax.xml.transform.OutputKeys.METHOD, "xml");
transformer.setOutputProperty("encoding", encoding);
transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT,"yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3" );

javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(this);
if (source == null) return "Corrupted XML document: " + this.toString();

java.io.StringWriter os = new java.io.StringWriter();
javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(os);
transformer.transform(source,result);

return os.toString ();
Tell others about this article:
Click here to submit this page to Stumble It