Java tutorial
//package com.java2s; /* * Sun Public License Notice * * The contents of this file are subject to the Sun Public License * Version 1.0 (the "License"). You may not use this file except in * compliance with the License. A copy of the License is available at * http://www.sun.com/ * * The Original Code is NetBeans. The Initial Developer of the Original * Code is Sun Microsystems, Inc. Portions Copyright 1997-2002 Sun * Microsystems, Inc. All Rights Reserved. */ import java.io.*; public class Main { /** * Escape passed string as XML attibute value * (<code><</code>, <code>&</code>, <code>'</code> and <code>"</code> * will be escaped. * Note: An XML processor returns normalized value that can be different. * * @param val a string to be escaped * * @return escaped value * @throws CharConversionException if val contains an improper XML character * * @since 1.40 */ public static String toAttributeValue(String val) throws CharConversionException { if (val == null) throw new CharConversionException("null"); // NOI18N if (checkAttributeCharacters(val)) return val; StringBuffer buf = new StringBuffer(); for (int i = 0; i < val.length(); i++) { char ch = val.charAt(i); if ('<' == ch) { buf.append("<"); continue; } else if ('&' == ch) { buf.append("&"); continue; } else if ('\'' == ch) { buf.append("'"); continue; } else if ('"' == ch) { buf.append("""); continue; } buf.append(ch); } return buf.toString(); } /** * Check if all passed characters match XML expression [2]. * @return true if no escaping necessary * @throws CharConversionException if contains invalid chars */ private static boolean checkAttributeCharacters(String chars) throws CharConversionException { boolean escape = false; for (int i = 0; i < chars.length(); i++) { char ch = chars.charAt(i); if (((int) ch) <= 93) { // we are UNICODE ']' switch (ch) { case 0x9: case 0xA: case 0xD: continue; case '\'': case '"': case '<': case '&': escape = true; continue; default: if (((int) ch) < 0x20) { throw new CharConversionException("Invalid XML character &#" + ((int) ch) + ";."); } } } } return escape == false; } }