quote XML String By Entity - Java XML

Java examples for XML:XML Entity

Description

quote XML String By Entity

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String str = "java2s.com";
        System.out.println(quotByEntity(str));
    }/*from  www . j a  v  a  2  s  .  c  o m*/

    static public String quotByEntity(String str) {
        if (str.indexOf('&') != -1) {
            int len = str.length();
            StringBuffer sb = new StringBuffer(len + 4 * 10);
            int offset = 0;
            int pos;
            do {
                if ((pos = str.indexOf('&', offset)) == -1) {
                    sb.append(str.substring(offset));
                    break;
                }

                sb.append(str.substring(offset, pos));
                sb.append("&");
                offset = pos + 1;
            } while (offset < len);

            str = sb.toString();
        }

        if (str.indexOf('<') != -1) {
            int len = str.length();
            StringBuffer sb = new StringBuffer(len + 3 * 10);
            int offset = 0;
            int pos;
            do {
                if ((pos = str.indexOf('<', offset)) == -1) {
                    sb.append(str.substring(offset));
                    break;
                }

                sb.append(str.substring(offset, pos));
                sb.append("&lt;");
                offset = pos + 1;
            } while (offset < len);

            str = sb.toString();
        }

        return str;
    }
}

Related Tutorials