Java XML Unescape unescapeXml(String src)

Here you can find the source of unescapeXml(String src)

Description

unescape Xml

License

Apache License

Declaration

static public String unescapeXml(String src) throws Exception 

Method Source Code

//package com.java2s;
/*// www . jav  a  2s . c o  m
 * 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();
    }
}

Related

  1. unescapeFromXML(String string)
  2. unescapeXML(final String s)
  3. unescapeXml(String input)
  4. unescapeXml(String input)
  5. unescapeXML(String s)
  6. unescapeXML(String str)
  7. unescapeXml(String str)
  8. unescapeXml(String str)
  9. unescapeXML(String text)