Java - Write code to Given a string, replace all the instances of XML special characters with their corresponding XML entities.

Requirements

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

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String string = "book2s.com";
        System.out.println(escapeForXML(string));
    }// w  ww. j  a v  a2  s  .  c  o m

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