Replace bad xml characters in given array by space - Java XML

Java examples for XML:XML String

Description

Replace bad xml characters in given array by space

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        char[] cbuf = new char[] { 'b', 'o', 'o', 'k', '2', 's', '.', 'c',
                'o', 'm', 'a', '1', };
        int off = 2;
        int len = 2;
        replaceBadXmlCharactersBySpace(cbuf, off, len);
    }/*  w w  w  .j  a v  a2  s.co  m*/

    /**
     * Replace bad xml characters in given array by space
     *
     * @param cbuf buffer to replace in
     * @param off  Offset from which to start reading characters
     * @param len  Number of characters to be replaced
     */
    public static void replaceBadXmlCharactersBySpace(char[] cbuf, int off,
            int len) {
        for (int i = off; i < off + len; i++) {
            if (isBadXmlCharacter(cbuf[i])) {
                cbuf[i] = '\u0020';
            }
        }
    }

    /**
     * Detect bad xml 1.0 characters
     *
     * @param c to detect
     * @return true if specified character valid, false otherwise
     */
    public static boolean isBadXmlCharacter(char c) {
        boolean cDataCharacter = c < '\u0020' && c != '\t' && c != '\r'
                && c != '\n';
        cDataCharacter |= (c >= '\uD800' && c < '\uE000');
        cDataCharacter |= (c == '\uFFFE' || c == '\uFFFF');
        return cDataCharacter;
    }
}

Related Tutorials