Java tutorial
//package com.java2s; //License from project: Apache License import org.w3c.dom.Element; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import java.io.StringWriter; public class Main { /** * Escapes backslashes ('\') with additional backslashes in a given String, returning a new, escaped String. * * @param value String to escape. Cannot be null. * @return escaped String. Never is null. */ public static String escapeBackslashes(String value) { StringBuilder buf = new StringBuilder(value); for (int looper = 0; looper < buf.length(); looper++) { char curr = buf.charAt(looper); char next = 0; if (looper + 1 < buf.length()) next = buf.charAt(looper + 1); if (curr == '\\') { if (next != '\\') { // only if not already escaped buf.insert(looper, '\\'); // escape backslash } looper++; // skip past extra backslash (either the one we added or existing) } } return buf.toString(); } public static String toString(Element e) { try { TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer xform = tfactory.newTransformer(); Source src = new DOMSource(e); java.io.StringWriter writer = new StringWriter(); Result result = new javax.xml.transform.stream.StreamResult(writer); xform.transform(src, result); return writer.toString(); } catch (Exception ex) { return "Unable to convert to string: " + ex.toString(); } } }