Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

public class Main {
    /**
     * Encode a string so that it can be safely used as text in an element
     * for XML output.
     * @param text the element text body.
     * @return a string so that it can be safely used as text in an element
     *       for XML output.
     */
    public static String escape(String text) {
        final StringBuffer sb = new StringBuffer();
        if (text != null) {
            char c;
            final int l = text.length();
            for (int i = 0; i < l; i++) {
                c = text.charAt(i);
                switch (c) {
                case '<':
                    sb.append("&lt;");
                    break;
                case '>': // only needed to avoid ]]>
                    sb.append("&gt;");
                    break;
                case '&':
                    sb.append("&amp;");
                    break;
                default:
                    if (c > Byte.MAX_VALUE) {
                        sb.append("&#x");
                        sb.append(Integer.toHexString(c));
                        sb.append(';');
                    } else {
                        sb.append(c);
                    }
                }
            }
        }
        return sb.toString();
    }
}