Java XML Unescape unescapeForXML(String string)

Here you can find the source of unescapeForXML(String string)

Description

Given a string, replace all the instances of XML entities with their corresponding XML special characters.

License

Open Source License

Parameter

Parameter Description
string The string to escape.

Return

A new string with special characters replaced.

Declaration

public static String unescapeForXML(String string) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /** Given a string, replace all the instances of XML entities
     *  with their corresponding XML special characters.  This is necessary to
     *  allow arbitrary strings to be encoded within XML.
     *//from   w w w  . j  av  a  2s  .com
     *  <p>In this method, we make the following translations:
     *  <pre>
     *  &amp;amp; becomes &amp
     *  &amp;quot; becomes "
     *  &amp;lt; becomes <
     *  &amp;gt; becomes >
     *  &amp;#10; becomes newline
     *  &amp;#13; becomes carriage return
     *  </pre>
     *  @see #escapeForXML(String)
     *
     *  @param string The string to escape.
     *  @return A new string with special characters replaced.
     */
    public static String unescapeForXML(String string) {
        string = substitute(string, "&amp;", "&");
        string = substitute(string, "&quot;", "\"");
        string = substitute(string, "&lt;", "<");
        string = substitute(string, "&gt;", ">");
        string = substitute(string, "&#10;", "\n");
        string = substitute(string, "&#13;", "\r");
        return string;
    }

    /** Replace all occurrences of <i>pattern</i> in the specified
     *  string with <i>replacement</i>.  Note that the pattern is NOT
     *  a regular expression, and that relative to the
     *  String.replaceAll() method in jdk1.4, this method is extremely
     *  slow.  This method does not work well with back slashes.
     *  @param string The string to edit.
     *  @param pattern The string to replace.
     *  @param replacement The string to replace it with.
     *  @return A new string with the specified replacements.
     */
    public static String substitute(String string, String pattern, String replacement) {
        int start = string.indexOf(pattern);

        while (start != -1) {
            StringBuffer buffer = new StringBuffer(string);
            buffer.delete(start, start + pattern.length());
            buffer.insert(start, replacement);
            string = new String(buffer);
            start = string.indexOf(pattern, start + replacement.length());
        }

        return string;
    }
}

Related

  1. unescapedKeyNameXml(final String name)
  2. unescapeFromXml(String escapedString)
  3. unescapeFromXML(String st)
  4. unescapeFromXML(String string)
  5. unescapeFromXML(String string)