Here you can find the source of nodeToString(Node node)
private static String nodeToString(Node node)
//package com.java2s; /*/*from w w w . j a v a 2 s .c o m*/ * ? Copyright IBM Corp. 2011, 2014 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ import java.io.StringWriter; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; 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.Node; public class Main { private static String NEWLINE = System.getProperty("line.separator"); private static String nodeToString(Node node) { StringWriter sw = new StringWriter(); try { Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); t.transform(new DOMSource(node), new StreamResult(sw)); } catch (TransformerException te) { throw new RuntimeException(te); } String asStr = sw.toString(); String xmlDecl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; String badStart = xmlDecl + "<"; if (asStr.startsWith(badStart)) { // missing newline after xmlDecl asStr = xmlDecl + NEWLINE + asStr.substring(xmlDecl.length()); } // convert the newline character in render-markup elements from // to 
 (hex encoding of same character), to be consistent // with the previous XML serializer. asStr = asStr.replace(" ", "
"); return asStr + NEWLINE; } }