Get a string representation of a DOM XML document

From CodeCodex

Implementations[edit]

Java[edit]

import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import org.w3c.dom.*;
   public String toXMLString(Document documentNode) {
      String html = null;
      try
      {
          TransformerFactory tFactory = TransformerFactory.newInstance();
          Transformer transformer = tFactory.newTransformer();
          //transformer.setOutputProperty("omit-xml-declaration", "yes");

          StringWriter sw = new StringWriter();
          StreamResult result = new StreamResult(sw);

          DOMSource source = new DOMSource( documentNode );
          transformer.transform( source, result );

          html = sw.getBuffer().toString();
      }
      catch (TransformerException exception)
      {
    	  html = null;
      }
      return html;
   }

OCaml[edit]

The to_string function in the Xml module converts XML to a string:

# Xml.to_string;;
- : Xml.xml -> string = <fun>