Java tutorial
//package com.java2s; import java.util.ArrayList; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { public static String serializeDocumentToXml(Document document) { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); Element documentElement = document.getDocumentElement(); serializeElement(sb, documentElement, 0); sb.append("\n"); return sb.toString(); } private static void serializeElement(StringBuilder sb, Element element, int tabIndex) { sb.append('\n'); for (int i = 0; i < tabIndex; i++) { sb.append('\t'); } sb.append("<"); sb.append(element.getTagName()); if (element.hasAttributes()) { NamedNodeMap attributes = element.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); sb.append(" "); sb.append(attribute.getNodeName()); sb.append("="); sb.append("\""); String value = attribute.getNodeValue(); sb.append(value.replace("\"", "\\\"")); sb.append("\""); } } sb.append(">"); NodeList nodeList = element.getChildNodes(); ArrayList<Element> childElements = new ArrayList<Element>(); for (int i = 0; i < nodeList.getLength(); i++) { Node childNode = nodeList.item(i); if (childNode instanceof Element) { childElements.add((Element) childNode); } } if (childElements.size() == 0) { sb.append(escapeInvalidCharacters(getTextContent(element))); } else { for (Element childElement : childElements) { serializeElement(sb, childElement, tabIndex + 1); } sb.append('\n'); for (int i = 0; i < tabIndex; i++) { sb.append('\t'); } } sb.append("</"); sb.append(element.getTagName()); sb.append(">"); } private static String escapeInvalidCharacters(String textContent) { if (textContent == null) { return null; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < textContent.length(); i++) { char c = textContent.charAt(i); switch (c) { case '<': sb.append("<"); break; case '>': sb.append(">"); break; case '\"': sb.append("""); break; case '\'': sb.append("'"); break; case '&': sb.append("&"); break; default: sb.append(c); break; } } return sb.toString(); } private static String getTextContent(Element element) { if (element == null) { return null; } Node textNode = element.getFirstChild(); if (textNode == null) { return ""; } if (textNode.getNodeType() != Node.TEXT_NODE) { throw new RuntimeException("Element " + element.getTagName() + "does not have text content"); } return textNode.getNodeValue(); } }