escape XML string - Android XML

Android examples for XML:XML String Escape

Description

escape XML string

Demo Code

/*******************************************************************************
 * 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 '&amp;'.
            if (c == '&')
                b.append("&amp;");
            // Escape '<' into '&lt;'.
            else if (c == '<')
                b.append("&lt;");
            // Escape '>' into '&gt;'.
            else if (c == '>')
                b.append("&gt;");
            // Escape '"' into '&quot;'.
            else if (c == '"')
                b.append("&quot;");
            // Escape ''' into '&#039;'.
            else if (c == '\'')
                b.append("&#039;");
            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();
    }
}

Related Tutorials