Android examples for XML:XML String Escape
escape XML string
/******************************************************************************* * Copyright (c) 2010 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ //package com.java2s; public class Main { public static void main(String[] argv) throws Exception { String text = "java2s.com"; System.out.println(escapeXMLstring(text)); }/*w w w .j a v a 2 s . c o m*/ /** @return Returns text with less-than and ampersands replaced by XML escapes. * @param text */ public static final String escapeXMLstring(final String text) { StringBuilder b = new StringBuilder(text.length() + 3); int i; for (i = 0; i < text.length(); ++i) { char c = text.charAt(i); // Escape '&' into '&'. if (c == '&') b.append("&"); // Escape '<' into '<'. else if (c == '<') b.append("<"); // Escape '>' into '>'. else if (c == '>') b.append(">"); // Escape '"' into '"'. else if (c == '"') b.append("""); // Escape ''' into '''. else if (c == '\'') b.append("'"); else if (c < 32 || c > 126) { // Other non-printable. Exact definition not clear. b.append("&#"); b.append((int) c); b.append(";"); } else b.append(c); } return b.toString(); } }