Java String Escape escapeXml(String str)

Here you can find the source of escapeXml(String str)

Description

Escapes XML entities in a String.

License

Apache License

Parameter

Parameter Description
str The <code>String</code> to escape.

Return

A new escaped String.

Declaration

private static String escapeXml(String str) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.*;

public class Main {
    private static Map xmlEntities = new HashMap();

    /**/*from  ww w.  j  a v  a 2 s  .  co m*/
     * <p> Escapes XML entities in a
     * <code>String</code>. </p>
     *
     * @param str The
     *            <code>String</code> to escape.
     * @return A new escaped
     * <code>String</code>.
     */
    private static String escapeXml(String str) {
        if (str == null) {
            return str;
        }
        StringBuffer buf = new StringBuffer(str.length() * 2);
        int i;
        for (i = 0; i < str.length(); ++i) {
            char ch = str.charAt(i);
            String entityName = getEntityName(ch);
            if (entityName == null) {
                if (ch > 0x7F) {
                    buf.append("&#");
                    buf.append((int) ch);
                    buf.append(';');
                } else {
                    buf.append(ch);
                }
            } else {
                buf.append('&');
                buf.append(entityName);
                buf.append(';');
            }
        }
        return buf.toString();
    }

    private static String getEntityName(char ch) {
        return (String) xmlEntities.get(Integer.toString(ch));
    }
}

Related

  1. escapeUnicodeString(final String input, final boolean escapeAscii)
  2. escapeUnsafeCharacters(String anyURI, boolean escapePercent)
  3. escapeWiki(String s)
  4. escapeXML(String message)
  5. escapeXML(String str)
  6. percentEncode(String s)
  7. percentEncode(String s)
  8. percentEncode(String value)
  9. percentEncode(String value, String encoding)