Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.*;

public class Main {
    public final static String XML_ESCAPE_DELIMITERS = "&'<>\"";

    /**
     * Replace all occurrences of the characters &, ', ", < and > by the escaped
     * characters &amp;, &quot;, &apos;, &lt; and &gt;
     */
    public static String XMLEscape(String s) {
        if (s == null) {
            return "";
        }

        boolean contains = false;
        for (int i = 0; i < XML_ESCAPE_DELIMITERS.length(); i++) {
            if (s.indexOf(XML_ESCAPE_DELIMITERS.charAt(i)) != -1) {
                contains = true;
            }
        }

        if (!contains) {
            return s;
        }

        if (s.length() == 0) {
            return s;
        }

        StringTokenizer tokenizer = new StringTokenizer(s, XML_ESCAPE_DELIMITERS, true);
        StringBuffer result = new StringBuffer();

        while (tokenizer.hasMoreElements()) {
            String substring = tokenizer.nextToken();

            if (substring.length() == 1) {
                switch (substring.charAt(0)) {

                case '&':
                    result.append("&amp;");
                    break;

                //case '\'' :
                //    result.append("&apos;");
                //    break;

                case ';':
                    result.append("\\;");
                    break;

                case '<':
                    result.append("&lt;");
                    break;

                case '>':
                    result.append("&gt;");
                    break;

                case '\"':
                    result.append("&quot;");
                    break;

                //                case '\n' :
                //                    result.append("\\n");
                //                    break;

                default:
                    result.append(substring);
                }
            } else {
                result.append(substring);
            }
        }

        return result.toString();
    }
}