Java tutorial
//package com.java2s; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { public static String domNode2String(Node node, boolean escapeStrings) { String ret = ""; switch (node.getNodeType()) { case Node.DOCUMENT_NODE: // recurse on each child NodeList nodes = node.getChildNodes(); if (nodes != null) { for (int i = 0; i < nodes.getLength(); i++) { ret += domNode2String(nodes.item(i), escapeStrings); } } break; case Node.ELEMENT_NODE: String name = node.getNodeName(); ret += "<" + name; NamedNodeMap attributes = node.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node current = attributes.item(i); ret += " " + current.getNodeName() + "=\"" + ((escapeStrings) ? escapeStringForXML(current.getNodeValue()) : current.getNodeValue()) + "\""; } ret += ">"; // recurse on each child NodeList children = node.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { ret += domNode2String(children.item(i), escapeStrings); } } ret += "</" + name + ">"; break; case Node.TEXT_NODE: ret += (escapeStrings) ? escapeStringForXML(node.getNodeValue()) : node.getNodeValue(); break; case Node.COMMENT_NODE: ret += "<!--" + node.getNodeValue() + "-->"; break; } return ret; } public static String escapeStringForXML(String aText) { final StringBuilder result = new StringBuilder(); final StringCharacterIterator iterator = new StringCharacterIterator(aText); char character = iterator.current(); while (character != CharacterIterator.DONE) { if (character == '<') { result.append("<"); } else if (character == '>') { result.append(">"); } else if (character == '\"') { result.append("""); } else if (character == '\'') { result.append("'"); } else if (character == '&') { result.append("&"); } else { //the char is not a special one //add it to the result as is result.append(character); } character = iterator.next(); } return result.toString(); } }