Java XML String Transform escapeBackslashes(String value)

Here you can find the source of escapeBackslashes(String value)

Description

Escapes backslashes ('\') with additional backslashes in a given String, returning a new, escaped String.

License

Apache License

Parameter

Parameter Description
value String to escape. Cannot be null.

Return

escaped String. Never is null.

Declaration

public static String escapeBackslashes(String value) 

Method Source Code

//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 {
    /**/*from   w ww.  j  ava  2 s .c  o  m*/
     * 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();
        }
    }
}

Related

  1. createXmlEventReaderOnXmlString(String xml, String docBaseUri)
  2. decodeHex(String hex)
  3. elementToXMLString(Object aElement)
  4. encode(final String value)
  5. encodeStringIntoMemento(String str)
  6. extractAndNormalizeEmbedPictures(String xmlFile, String odtFile, String parentDir, String imgBaseDir)
  7. extractElement(String xml, String tagName)
  8. extractText(Node n, StringBuffer buf)
  9. fileToXMLString(String filename)