unescape Xml - Java XML

Java examples for XML:XML String Escape

Description

unescape Xml

Demo Code



public class Main{
    public static String unescapeXml(String s, EntityNamespace entities) {
        final StringBuilder b = new StringBuilder(s.length());
        final char[] as = s.toCharArray();
        for (int i = 0; i < as.length; i++) {
            char c = as[i];
            if (c == '&') {
                int j = ++i;
                for (; i < as.length && as[i] != ';'; i++)
                    ;//from  ww w .  java2  s . co m
                b.append(getEntityValue(new String(as, j, i - j), entities));
            } else {
                b.append(c);
            }
        }
        return b.toString();
    }
    /**
     * Parses an XML entity value such as <code>#xFD45</code> or
     * <code>#6582</code>. Either returns <code>-1</code> if the first character
     * was not <code>#</code>, <code>-2</code> if the first character was
     * <code>#</code> but the value could not be parsed or the character that
     * was parsed.
     */
    public static int getEntityValue(String entity) {
        final char[] entityCharacters = entity.toCharArray();
        if (entityCharacters.length >= 1) {
            if (entityCharacters[0] == '#') {
                if (entityCharacters.length >= 2) {
                    if (entityCharacters[1] == 'x') {
                        try {
                            return Integer
                                    .parseInt(entity.substring(2), 16);
                        } catch (NumberFormatException e) {
                        }
                    } else {
                        try {
                            return Integer
                                    .parseInt(entity.substring(1), 10);
                        } catch (NumberFormatException e) {
                        }
                    }
                }
                return -2;
            }
        }
        return -1;
    }
    /**
     * Returns the parsed entity code (not including the leading <code>&</code>
     * or the trailing <code>;</code>) or <code>null</code> if the code could
     * not be parsed.
     */
    public static String getEntityValue(String entity,
            EntityNamespace entities) {
        int e = getEntityValue(entity);
        if (e >= 0) {
            return Character.toString((char) e);
        } else if (e == -2) {
            return null;
        } else {
            return entities.getEntity(entity);
        }
    }
}

Related Tutorials