×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Boulty Doolin
Added: Sep 28, 2017 2:01 PM
Views: 4
Get the contents of an XML document object as a string with optional pretty print.
  1. import org.w3c.dom.Document;
  2.  
  3. import javax.xml.transform.OutputKeys;
  4. import javax.xml.transform.Transformer;
  5. import javax.xml.transform.TransformerFactory;
  6. import javax.xml.transform.dom.DOMSource;
  7. import javax.xml.transform.stream.StreamResult;
  8. import java.io.StringWriter;
  9.  
  10. public class TempWrapper {
  11.    
  12.     public String getXMLString(Document document, boolean prettyPrint) {
  13.         try {
  14.             TransformerFactory transformerFactory = TransformerFactory.newInstance();
  15.             Transformer transformer = transformerFactory.newTransformer();
  16.             transformer.setOutputProperty(OutputKeys.METHOD, "xml");
  17.             if (prettyPrint) {
  18.                 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  19.                 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  20.                 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(2));
  21.             }
  22.  
  23.             StringWriter stringWriter = new StringWriter();
  24.             StreamResult result = new StreamResult(stringWriter);
  25.             DOMSource source = new DOMSource(document.getDocumentElement());
  26.  
  27.             transformer.transform(source, result);
  28.             String xmlString = stringWriter.toString();
  29.             stringWriter.close();
  30.             return xmlString;
  31.         } catch (Exception e) {
  32.             throw new RuntimeException(e);
  33.         }
  34.     }    
  35. }
  36.