encode Text For XML Element - Android XML

Android examples for XML:XML Element

Description

encode Text For XML Element

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String sValue = "java2s.com";
        System.out.println(encodeTextForElement(sValue));
    }/*  w ww.  j  a v  a  2s.c  om*/

    public static String encodeTextForElement(String sValue) {
        // Change all unsafe XML characters into their safe ones
        String sReturnVal = fixXmlString(sValue);
        sReturnVal = sReturnVal.replace("\r\n", " ").replace("\r", "")
                .replace("\n", "");
        return sReturnVal;
    }

    public static String fixXmlString(String sValue) {
        // Change all unsafe XML characters into their safe ones
        String sReturnVal = sValue.replace("&", "&");
        sReturnVal = sReturnVal.replace("'", "'");
        sReturnVal = sReturnVal.replace("\"", """);
        sReturnVal = sReturnVal.replace("<", "&lt;");
        return sReturnVal.replace(">", "&gt;");
    }
}

Related Tutorials