convert Special Chars for XML String - Android XML

Android examples for XML:XML String

Description

convert Special Chars for XML String

Demo Code

/*L// w ww . j av a  2s . c  o m
 * Copyright SAIC, SAIC-Frederick.
 *
 * Distributed under the OSI-approved BSD 3-Clause License.
 * See http://ncip.github.com/caadapter/LICENSE.txt for details.
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String s = "java2s.com";
        System.out.println(convertSpecialChars(s));
    }

    private StringBuffer xmlString;

    public static String convertSpecialChars(String s) {
        StringBuffer stringbuffer = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '&')
                stringbuffer.append("&amp;");
            else if (c == '<')
                stringbuffer.append("&lt;");
            else if (c == '>')
                stringbuffer.append("&gt;");
            else if (c == '"')
                stringbuffer.append("&quot;");
            else if (c == '\'')
                stringbuffer.append("&apos;");
            else
                stringbuffer.append(c);
        }
        return stringbuffer.toString();
    }

    public void append(String s) {
        xmlString.append(s);
    }

    public String toString() {
        return xmlString.toString();
    }
}

Related Tutorials