Skip to content

Instantly share code, notes, and snippets.

@harschware
Created June 30, 2011 22:16
Show Gist options
  • Select an option

  • Save harschware/1057417 to your computer and use it in GitHub Desktop.

Select an option

Save harschware/1057417 to your computer and use it in GitHub Desktop.
lets you print a W3C DOM Object
package com.cray.utils;
import java.io.StringWriter;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
public class DomPrinter {
public static final TransformerFactory tfactory = TransformerFactory.newInstance();
public static final Transformer xform;
static {
try {
xform = tfactory.newTransformer();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
} // end try/catch
}
/**
*
* @see http://blogs.oracle.com/reynolds/entry/printing_xml
* @param doc
* @return
*/
public static String convertDom( Document doc ) {
// First of all create an empty org.w3c.dom.XMLTransform.
// Then wrap the DOM into a javax.xml.transform.Source.
javax.xml.transform.Source src = new DOMSource(doc);
//Now create a java.io.StringWriter to receive the output and wrap it into a javax.xml.transform.stream.StreamResult.
StringWriter writer = new StringWriter();
Result result = new StreamResult(writer);
// Finally use your empty transform to read from the source (your XML document in DOM format), apply a transform (a do nothing transform) and write the result (to your StreamResult which in turn is based on a StringWriter).
try {
xform.transform(src, result);
} catch (TransformerException e) {
e.printStackTrace();
} // end try/catch
// We can now extract the DOM as a text string by using the toString method on the StringWriter that we created.
return writer.toString();
} // end method
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment