Java XML Escape escapeXML(String s)

Here you can find the source of escapeXML(String s)

Description

escape XML

License

Artistic License

Declaration

public static String escapeXML(String s) 

Method Source Code

//package com.java2s;
/**/*ww w. ja  va 2 s  .  c  o  m*/
 * Copyright (C) 2011 Inqwell Ltd
 *
 * You may distribute under the terms of the Artistic License, as specified in
 * the README file.
 */

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

public class Main {
    public static String escapeXML(String s) {
        final StringBuilder result = new StringBuilder();
        final StringCharacterIterator iterator = new StringCharacterIterator(s);
        char ch = iterator.current();
        while (ch != CharacterIterator.DONE) {
            if (ch == '<') {
                result.append("&lt;");
            } else if (ch == '>') {
                result.append("&gt;");
            } else if (ch == '\"') {
                result.append("&quot;");
            } else if (ch == '\'') {
                result.append("&#039;");
            } else if (ch == '&') {
                result.append("&amp;");
            } else if ((ch >= '\u0000' && ch <= '\u001F') || (ch >= '\u007F' && ch <= '\u009F')
                    || (ch >= '\u2000' && ch <= '\u20FF')) {
                addCharEntity(ch, result);
            } else {
                result.append(ch);
            }
            ch = iterator.next();
        }
        return result.toString();
    }

    private static void addCharEntity(int i, StringBuilder sb) {
        String padding = "";
        if (i <= 9) {
            padding = "00";
        } else if (i <= 99) {
            padding = "0";
        } else {
            // no prefix
        }
        String number = padding + String.valueOf(i);
        sb.append("&#" + number + ";");
    }
}

Related

  1. escape4XML(long study_id, String xmlStr)
  2. escapeNonXmlTagSymbols(String string)