This is a dumping ground of software development topics that I've run across and found interesting (mainly .NET development). Many topics are covered more thoroughly in other places, and much of the information is gleaned from other places, and I'll try to credit those sources when possible.

Thursday, May 03, 2007

OuterXml for Java

Java can be extremely frustrating, particularily because there always seems to be many many different ways to do a simple task. For example, I needed to get a fragment from an XML document which seems easy enough. .NET has the XmlNode class which has a property OuterXml. Done. However, no such simple equivalent exists for Java, at least in my limited experience. I don't claim to be an XML expert, so I'm not about to write a diatribe. After a couple of hours, I found this guy's blog, which I used as a basis for the method below. You can figure out how to get a org.w3c.dom.Node object, that's another painful tale...

public static String getOuterXml(Node node)
throws TransformerConfigurationException, TransformerException
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty("omit-xml-declaration", "yes");

StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(node), new StreamResult(writer));
return writer.toString();


Bharat said...

Excellent post...


alittledog said...

Thanks. Trying to find a simple example was difficult for such a simple activity. Again... THANKS!