Java tutorial
//package com.java2s; //License from project: Open Source License import java.io.StringWriter; import java.io.Writer; import java.util.Map; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Node; import com.google.common.collect.ImmutableMap; public class Main { public static String serialize(Node doc) throws Exception { StringWriter outText = new StringWriter(); serialize(new DOMSource(doc), outText); return outText.toString(); } public static void serialize(Source source, Writer writer) throws Exception { serialize(source, writer, ImmutableMap.of(OutputKeys.ENCODING, "UTF-8", OutputKeys.INDENT, "yes")); } public static void serialize(Source source, Writer writer, Map<String, String> properties) throws Exception { StreamResult sr = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = null; t = tf.newTransformer(); for (Map.Entry<String, String> me : properties.entrySet()) { t.setOutputProperty(me.getKey(), me.getValue()); } t.transform(source, sr); } }