Encode String for XML attribute
In this chapter you will learn:
Encode Xml Attribute
We have to escape certain characters for attribute value.
For example, cannot use <
directly in attribute,
we have to use <
. The following code encodes
string for attribute.
public class Main {
public static String encodeXmlAttribute(String str) {
if (str == null)
return null;
/*from j a v a 2s .c o m*/
int len = str.length();
if (len == 0)
return str;
StringBuffer encoded = new StringBuffer();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if (c == '<')
encoded.append("<");
else if (c == '\"')
encoded.append(""");
else if (c == '>')
encoded.append(">");
else if (c == '\'')
encoded.append("'");
else if (c == '&')
encoded.append("&");
else
encoded.append(c);
}
return encoded.toString();
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » XML