Java tutorial
//package com.java2s; //License from project: Open Source License import org.w3c.dom.Document; import org.w3c.dom.Node; public class Main { /** This method goes through and adds formatting as necessary so that the XML is human readable * TODO work out why we can't put space in front of the first element */ protected static void addFormatting(Document outDoc) { // First we want a space before the first element addFormatting(outDoc, outDoc.getDocumentElement(), ""); } /** Goes through and adds newlines and indent to the current node and all its children * @param current the current node * @param indent the current level of indent this is increased recursively*/ private static void addFormatting(Document doc, Node current, String indent) { // go through each of the children adding space as required Node child = current.getFirstChild(); String childIndent = indent + "\t"; while (child != null) { Node nextChild = child.getNextSibling(); if (child.getNodeType() != Node.TEXT_NODE) { // Only if we aren't a text node do we add the space current.insertBefore(doc.createTextNode("\n" + childIndent), child); if (child.hasChildNodes()) { addFormatting(doc, child, childIndent); } if (nextChild == null) { // Because this is the last child, we need to add some space after it current.appendChild(doc.createTextNode("\n" + indent)); } } child = nextChild; } } }