Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright (C) 2014 Dell, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    static public String unescapeXml(String src) throws Exception {
        if (src == null || src.trim().length() == 0)
            return src;

        StringBuilder result = new StringBuilder();
        int length = src.length();

        for (int i = 0; i < length; i++) {
            char ch = src.charAt(i);

            if (ch != '&') {
                result.append(ch);
                continue;
            }

            int pos = src.indexOf(";", i);
            if (pos < 0) {
                result.append(ch);
                continue;
            }

            if (src.charAt(i + 1) == '#') {
                String esc = "";
                try {
                    esc = src.substring(i + 2, pos);
                    int val = Integer.parseInt(src.substring(i + 2, pos), 16);
                    result.append((char) val);
                    i = pos;
                    continue;
                } catch (Exception ex) {
                    String msg = "Something wrong with hex code \"" + esc + "\"";
                    throw new Exception(msg, ex);
                }
            }

            String esc = src.substring(i, pos + 1);
            if (esc.equals("&amp;"))
                result.append('&');
            else if (esc.equals("&lt;"))
                result.append('<');
            else if (esc.equals("&gt;"))
                result.append('>');
            else if (esc.equals("&quot;"))
                result.append('"');
            else if (esc.equals("&apos;"))
                result.append('\'');
            else {
                String msg = "Unknown escape \"" + esc + "\"";
                throw new Exception(msg);
            }
            i = pos;
        }

        return result.toString();
    }
}