Java tutorial
//package com.java2s; import java.io.IOException; import java.io.OutputStream; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { private final static String internal = " "; public static void logXMLNode(Document doc, OutputStream output) { String nodeStr = retrieveDocumentAsString(doc); try { output.write(nodeStr.getBytes()); output.close(); } catch (IOException ioe) { System.out.println("There happens some error when reading the xml fragment"); } } public static String retrieveDocumentAsString(Document doc) { Node node = doc.getDocumentElement(); return retrieveNodeAsString(node); } public static String retrieveNodeAsString(Node node) { String nodeStr = new String("<"); nodeStr += node.getNodeName() + internal; if (node.hasAttributes()) { NamedNodeMap attrs = node.getAttributes(); // add the attrubite name-value pairs for (int i = 0; i < attrs.getLength(); i++) { Node a = attrs.item(i); nodeStr += a.getNodeName() + "=" + a.getNodeValue() + internal; } } if (node.hasChildNodes()) { nodeStr += ">\n"; NodeList ns = node.getChildNodes(); for (int i = 0; i < ns.getLength(); i++) { nodeStr += logXMLSubNode(ns.item(i), 1); } nodeStr += "<" + node.getNodeName() + "/>\n"; } else { nodeStr += "/>\n"; } return nodeStr; } private static String logXMLSubNode(Node node, int deepth) { int i; String nodeStr = new String(); String interStr = new String(); for (i = 0; i < deepth; i++) interStr += "\t"; nodeStr += interStr + "<" + node.getNodeName() + internal; if (node.hasAttributes()) { NamedNodeMap attrs = node.getAttributes(); // add the attrubite name-value pairs for (i = 0; i < attrs.getLength(); i++) { Node a = attrs.item(i); nodeStr += a.getNodeName() + "=" + a.getNodeValue() + internal; } } if (node.hasChildNodes()) { nodeStr += ">\n"; NodeList ns = node.getChildNodes(); for (i = 0; i < ns.getLength(); i++) { nodeStr += logXMLSubNode(ns.item(i), deepth + 1); } nodeStr += interStr + "</" + node.getNodeName() + ">\n"; } else { if (node.getNodeValue() != null) { nodeStr += ">" + node.getNodeValue() + "<" + node.getNodeName(); } nodeStr += "/>\n"; } return nodeStr; } }