Java tutorial
//package com.java2s; /* * www.openamf.org * * Distributable under LGPL license. * See terms of license at gnu.org. */ import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { private static void appendChildren(Node node, StringBuffer sb) { if (node.hasChildNodes()) { NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { sb.append(convertDOMToString(children.item(i))); } } } public static String convertDOMToString(Node node) { StringBuffer sb = new StringBuffer(); if (node.getNodeType() == Node.TEXT_NODE) { sb.append(node.getNodeValue()); } else { String currentTag = node.getNodeName(); sb.append('<'); sb.append(currentTag); appendAttributes(node, sb); sb.append('>'); if (node.getNodeValue() != null) { sb.append(node.getNodeValue()); } appendChildren(node, sb); appendEndTag(sb, currentTag); } return sb.toString(); } private static void appendAttributes(Node node, StringBuffer sb) { if (node instanceof Element) { NamedNodeMap nodeMap = node.getAttributes(); for (int i = 0; i < nodeMap.getLength(); i++) { sb.append(' '); sb.append(nodeMap.item(i).getNodeName()); sb.append('='); sb.append('"'); sb.append(nodeMap.item(i).getNodeValue()); sb.append('"'); } } } private static void appendEndTag(StringBuffer sb, String currentTag) { sb.append('<'); sb.append('/'); sb.append(currentTag); sb.append('>'); } }