Java Utililty Methods XML Encode

List of utility methods to do XML Encode

Description

The list of methods to do XML Encode are organized into topic(s).

Method

StringXMLEncode(final String value)
encodes a value for safe use in XML
String newValue = value.toString();
final String[] reps = new String[] { "&", "&amp;", "<", "&lt;", ">", "&gt;", "\"", "&quot;", "'",
        "&apos;" };
for (int i = 0; i < reps.length; i += 2)
    newValue = newValue.replace(reps[i], reps[i + 1]);
return newValue;
StringxmlEncode(String in)
xml Encode
StringBuffer out = new StringBuffer();
for (int i = 0; i < in.length(); i++) {
    char c = in.charAt(i);
    if (c == '<') {
        out.append("&gt;");
    } else if (c == '>') {
        out.append("&lt;");
    } else if (c == '&') {
...
StringXMLEncode(String name)

This is a helper method which converts any spaces in a string to a legal underscore.

StringBuilder buffer = new StringBuilder(name.length());
for (int i = 0; i < name.length(); i++) {
    char c = name.charAt(i);
    if (c == '_') {
        buffer.append("__");
    } else if (c == ' ') {
        buffer.append("_");
    } else {
...
StringxmlEncode(String s)
XML encode a string.
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); ++i) {
    char c = s.charAt(i);
    switch (c) {
    case '&':
        sb.append("&amp;");
        break;
    case '<':
...
StringxmlEncode(String s)
Encode string to XML.
return s.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll(">", "&gt;").replaceAll("<", "&lt;")
        .replaceAll("'", "&apos;");
StringxmlEncode(String s)
Convert given string in XML friendly version.
StringBuilder builder = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    if (c == '<' || c == '>' || c == '&') {
        builder.append("&#" + (int) c + ";");
    } else {
        builder.append(c);
return builder.toString();
StringxmlEncode(String s)
xml Encode
boolean changed = false;
char c;
StringBuffer sb = null;
for (int i = 0; i < s.length(); i++) {
    c = s.charAt(i);
    if (c < 0xa) {
        if (!changed) {
            if (i > 0)
...
StringxmlEncode(String s)
xml Encode
if (s == null)
    return null;
StringBuilder sb = new StringBuilder(s.length() + 16);
for (int i = 0, n = s.length(); i < n; i++) {
    char c = s.charAt(i);
    switch (c) {
    case '&':
        sb.append("&amp;");
...
StringxmlEncode(String str)
Replaces &, <, >, " in a string with their respective XML representation
if (str == null)
    return null;
str = str.replace("&", "&amp;");
str = str.replace("<", "&lt;");
str = str.replace(">", "&gt;");
str = str.replace("\"", "&quot;");
return str;
StringxmlEncode(String str)
xml Encode
return str.replace("&", "&amp;").replace("<", "&lt;").replace("<", "&gt;").replace("\"", "&quot;")
        .replace("'", "&apos;");