Here you can find the source of nodeToString(Object node)
public static String nodeToString(Object node)
//package com.java2s; /******************************************************************************* * Copyright (c) 2014 Gabriel Skantze./*from ww w . ja v a 2 s .c o m*/ * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * Gabriel Skantze - initial API and implementation ******************************************************************************/ import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; public class Main { public static String nodeToString(Object node) { String result = ""; if (node instanceof String) { String str = ((String) node).replaceAll("\\s+", " ").trim(); result += str; } else if (node instanceof Text) { String str = ((Text) node).getTextContent() .replaceAll("\\s+", " ").trim(); result += str; } else if (node instanceof Element) { Element elem = (Element) node; Set namespaces = collectNamespaces(elem); result += "<" + elem.getTagName(); for (int j = 0; j < elem.getAttributes().getLength(); j++) { Attr attr = (Attr) elem.getAttributes().item(j); if (attr.getNamespaceURI() != null && attr.getNamespaceURI().equals( "http://www.w3.org/2000/xmlns/") && !namespaces.contains(attr.getValue())) continue; result += " " + attr.getName() + "=\"" + attr.getValue() + "\""; } if (elem.getChildNodes().getLength() == 0) { result += "/>"; } else { result += ">"; ArrayList<Object> children = new ArrayList<Object>(); for (int i = 0; i < elem.getChildNodes().getLength(); i++) { children.add(elem.getChildNodes().item(i)); } result += nodesToString(children); result += "</" + elem.getTagName() + ">"; } } return result; } public static Set<String> collectNamespaces(Element elem) { Set<String> set = new HashSet<String>(); collectNamespaces(elem, set); return set; } private static void collectNamespaces(Element elem, Set set) { if (elem.getNamespaceURI() != null) { set.add(elem.getNamespaceURI()); } for (int j = 0; j < elem.getAttributes().getLength(); j++) { Attr attr = (Attr) elem.getAttributes().item(j); if (attr.getNamespaceURI() != null) { set.add(attr.getNamespaceURI()); } } for (int i = 0; i < elem.getChildNodes().getLength(); i++) { Node child = elem.getChildNodes().item(i); if (child instanceof Element) { collectNamespaces((Element) child, set); } } } public static String nodesToString(List<Object> nodes) { String result = ""; for (Object node : nodes) { result += nodeToString(node); } return result; } }