Escapes the characters in a String using XML entities. - Java XML

Java examples for XML:XML String Escape

Introduction

The following code shows how to Escapes the characters in a String using XML entities.

Demo Code

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;

public class Main{
    public static void main(String[] argv){
        String src = "java2s.com";
        System.out.println(escape(src));
    }/*www  .j av  a 2 s .  c o m*/
    private static final String[] ESCAPES;

    static {
        int size = '>' + 1; // '>' is the largest escaped value
        ESCAPES = new String[size];
        ESCAPES['<'] = "&lt;";
        ESCAPES['>'] = "&gt;";
        ESCAPES['&'] = "&amp;";
        ESCAPES['\''] = "&#039;";
        ESCAPES['"'] = "&#034;";
    }
    
    /**
     * <p>
     * Escapes the characters in a <code>String</code> using XML entities.
     * 
     * @param str
     *            the <code>String</code> to escape, may be null
     * @return a new escaped <code>String</code>, <code>null</code> if null
     *         string input
     */
    public static String escape(String src) {

        if (src == null) {
            return src;
        }

        // First pass to determine the length of the buffer so we only allocate
        // once
        int length = 0;
        for (int i = 0; i < src.length(); i++) {
            char c = src.charAt(i);
            String escape = getEscape(c);
            if (escape != null) {
                length += escape.length();
            } else {
                length += 1;
            }
        }

        // Skip copy if no escaping is needed
        if (length == src.length()) {
            return src;
        }

        // Second pass to build the escaped string
        StringBuilder buf = new StringBuilder(length);
        for (int i = 0; i < src.length(); i++) {
            char c = src.charAt(i);
            String escape = getEscape(c);
            if (escape != null) {
                buf.append(escape);
            } else {
                buf.append(c);
            }
        }
        return buf.toString();
    }
    /**
     * <p>
     * Escapes the characters in a {@code String} using XML entities only if the
     * passed boolean is {@code true}.
     * 
     * @param str
     *            the {@code String} to escape.
     * @return a new escaped {@code String} if {@code shouldEscape} is set to
     *         {@code true}, an unchanged {@code String} otherwise.
     */
    public static String escape(boolean shouldEscape, String src) {
        if (shouldEscape) {
            return escape(src);
        }
        return src;
    }
    private static String getEscape(char c) {
      if (c < ESCAPES.length) {
          return ESCAPES[c];
      } else {
          return null;
      }
  }
}

Related Tutorials