// Collection of code snippets by Arne VajhÃ¸j 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.io.IOException;
import java.io.PrintStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class WriteW3CDOMCustom {
    public static void writeXML(PrintStream ps, String ind, Node parent) {
        switch (parent.getNodeType()) {
            case Node.ELEMENT_NODE :
                ps.print(ind + "<" + parent.getNodeName());
                NamedNodeMap atts = parent.getAttributes();
                for (int i = 0; i < atts.getLength(); i++) {
                    ps.print(" " + atts.item(i).getNodeName() + "=\"" + atts.item(i).getNodeValue() + "\"");
                }
                NodeList childs = parent.getChildNodes();
                if (childs.getLength() == 0) {
                    ps.println("/>");
                } else {
                    ps.println(">");
                    for (int i = 0; i < childs.getLength(); i++) {
                        writeXML(ps, ind + "   ", (Node) childs.item(i));
                    }
                    ps.println(ind + "<" + parent.getNodeName() + "/>");
                }
                break;
            case Node.TEXT_NODE :
                if(!parent.getNodeValue().trim().equals("")) {
                    ps.println(ind + parent.getNodeValue().trim());
                }
                break;
            default :
                // nothing
        }
        return;
    }
    public static void main(String[] args) {
        try {
            // læs fra fil til DOM træ
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse("C:\\test.xml");
            // udskriv DOM træ
            writeXML(System.out, "", doc.getDocumentElement());
        } catch (FactoryConfigurationError e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }
}
