Escape invalid characters that are not allowed in XML element names if the name is not still valid, then replace it with INVALID_ELEMENT_NAME - Android XML

Android examples for XML:XML String Escape

Description

Escape invalid characters that are not allowed in XML element names if the name is not still valid, then replace it with INVALID_ELEMENT_NAME

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String elementName = "java2s.com";
        System.out.println(getEscapedElementName(elementName));
    }/*from  ww  w . ja  v a  2  s  . co m*/

    /** */
    public static final String INVALID_ELEMENT_NAME = "unknown";

    /**
     * Escape invalid characters that are not allowed in XML element names if the name is not still valid, then replace it with
     * INVALID_ELEMENT_NAME
     *
     */
    public static String getEscapedElementName(String elementName) {

        if (elementName == null || elementName.length() == 0)
            elementName = INVALID_ELEMENT_NAME;

        // replace whitespaces and other reserved characters with underscore
        elementName = elementName.replaceAll("[^A-Za-z0-9_-]", "_");

        // add leading unerscore if the name starts with invalid character or if it starts with xml (any case)
        if (!elementName.substring(0, 1).matches("[A-Z]|_|[a-z]")
                || elementName.toLowerCase().startsWith("xml")) {
            elementName = "_" + elementName;
        }

        return elementName;
    }
}

Related Tutorials