Java examples for XML:XML Attribute
Encode XML attribute value.
//package com.java2s; public class Main { public static void main(String[] argv) throws Exception { String str = "java2s.com"; System.out.println(escapeAttribute(str)); }/*from ww w . j a va2s .c om*/ /** * Encode an attribute value. * This assumes use of " as the attribute value delimiter. * @param str the string to convert. * @return the converted string. */ public static String escapeAttribute(String str) { final StringBuilder b = new StringBuilder(); final char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; ++i) { final char c = chars[i]; switch (c) { case '<': b.append("<"); break; case '>': b.append(">"); break; case '&': b.append("&"); break; case '"': b.append("""); break; default: b.append(c); } } return b.toString(); } }