Java tutorial
//package com.java2s; import org.w3c.dom.*; public class Main { public static String printNode(Node node) { StringBuffer sBuffer = new StringBuffer(); printNode(sBuffer, node); return sBuffer.toString(); } /** Takes XML node and prints to String. * * @param node Element to print to String * @return XML node as String */ private static void printNode(StringBuffer sBuffer, Node node) { if (node.getNodeType() == Node.TEXT_NODE) { sBuffer.append(encodeXMLText(node.getNodeValue().trim())); } else if (node.getNodeType() == Node.CDATA_SECTION_NODE) { sBuffer.append("<![CDATA["); sBuffer.append(node.getNodeValue()); sBuffer.append("]]>"); } else if (node.getNodeType() == Node.ELEMENT_NODE) { Element el = (Element) node; sBuffer.append("<").append(el.getTagName()); NamedNodeMap attribs = el.getAttributes(); for (int i = 0; i < attribs.getLength(); i++) { Attr nextAtt = (Attr) attribs.item(i); sBuffer.append(" ").append(nextAtt.getName()).append("=\"").append(nextAtt.getValue()).append("\""); } NodeList nodes = node.getChildNodes(); if (nodes.getLength() == 0) { sBuffer.append("/>"); } else { sBuffer.append(">"); for (int i = 0; i < nodes.getLength(); i++) { printNode(sBuffer, nodes.item(i)); } sBuffer.append("</").append(el.getTagName()).append(">"); } } } /** * Handles XML encoding of text, e.g. & to & * * @param sText Text to XML encode * @return XML Encoded text */ public static String encodeXMLText(String sText) { StringBuffer sBuff2 = new StringBuffer(sText); StringBuffer sNewBuff = new StringBuffer(); for (int i = 0; i < sBuff2.length(); i++) { char currChar = sBuff2.charAt(i); Character currCharObj = new Character(sBuff2.charAt(i)); if (currChar == '&') { if ((sBuff2.length() - 1 - i) >= 4 && sBuff2.charAt(i + 1) == 'a' && sBuff2.charAt(i + 2) == 'm' && sBuff2.charAt(i + 3) == 'p' && sBuff2.charAt(i + 4) == ';') { i = i + 4; sNewBuff.append("&"); } else { sNewBuff.append("&"); } } else if (currChar == '>') { sNewBuff.append(">"); } else if (currChar == '<') { sNewBuff.append("<"); } else { sNewBuff.append(currChar); } } return sNewBuff.toString(); } }