Java XML Sanitize sanitizeXmlTypeName(String name)

Here you can find the source of sanitizeXmlTypeName(String name)

Description

Since XML names can not contain all characters JSON names can, we may need to replace characters.

License

Open Source License

Declaration

public static String sanitizeXmlTypeName(String name) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*from  www  .j a v a  2 s.  c  o m*/
     * Since XML names can not contain all characters JSON names can, we may
     * need to replace characters. Let's start with trivial replacement of
     * ASCII characters that can not be included.
     */
    public static String sanitizeXmlTypeName(String name) {
        StringBuilder sb;
        int changes = 0;
        // First things first: remove array types' trailing[]...
        if (name.endsWith("[]")) {
            do {
                name = name.substring(0, name.length() - 2);
                ++changes;
            } while (name.endsWith("[]"));
            sb = new StringBuilder(name);
            // do trivial pluralization attempt
            if (name.endsWith("s")) {
                sb.append("es");
            } else {
                sb.append('s');
            }
        } else {
            sb = new StringBuilder(name);
        }
        for (int i = 0, len = name.length(); i < len; ++i) {
            char c = name.charAt(i);
            if (c > 127)
                continue;
            if (c >= 'a' && c <= 'z')
                continue;
            if (c >= 'A' && c <= 'Z')
                continue;
            if (c >= '0' && c <= '9')
                continue;
            if (c == '_' || c == '.' || c == '-')
                continue;
            // Ok, need to replace
            ++changes;
            if (c == '$') {
                sb.setCharAt(i, '.');
            } else {
                sb.setCharAt(i, '_');
            }
        }
        if (changes == 0) {
            return name;
        }
        return sb.toString();
    }
}

Related

  1. sanitizeJson4XML(String jsonString)
  2. sanitizeXML(String xml)
  3. SanitizeXmlString(String xml)