Java XML Quote quoteXMLValue(Object o)

Here you can find the source of quoteXMLValue(Object o)

Description

Convert the object into XML safe string

License

LGPL

Parameter

Parameter Description
o The object

Return

The string

Declaration

@SuppressWarnings({ "PMD.CyclomaticComplexity" })
public static String quoteXMLValue(Object o) 

Method Source Code

//package com.java2s;
/**/*w  ww .  j  a  v  a  2 s  .  c  o m*/
 * CC-LGPL 2.1
 * http://creativecommons.org/licenses/LGPL/2.1/
 */

public class Main {
    /**
     * Convert the object into XML safe string
     *
     * @param o The object
     * @return The string
     */
    @SuppressWarnings({ "PMD.CyclomaticComplexity" })
    public static String quoteXMLValue(Object o) {
        if (o == null) {
            return null;
        }

        String s = o.toString();
        StringBuilder str = new StringBuilder(s.length() * 5 / 4);
        int seqStart = 0;
        int seqEnd = 0;

        for (int count = 0; count < s.length(); count++) {
            char ch = s.charAt(count);
            if (ch == '<' || ch == '>' || ch == '"' || ch == '&' || ((int) ch) > 192 || ((int) ch) == 26) {
                if (seqEnd > seqStart) {
                    str.append(s.substring(seqStart, seqEnd));
                }

                if (ch == '"') {
                    str.append("&quot;");
                } else if (ch == '<') {
                    str.append("&lt;");
                } else if (ch == '>') {
                    str.append("&gt;");
                } else if (ch == '&') {
                    str.append("&amp;");
                } else if ((int) ch == 26) {
                    str.append("_");
                } else {
                    str.append("&#");
                    str.append(Integer.toString(ch));
                    str.append(';');
                }
                seqStart = count + 1;
            } else {
                seqEnd = count + 1;
            }
        }
        if (seqEnd > seqStart) {
            str.append(s.substring(seqStart, seqEnd));
        }

        return str.toString();
    }
}

Related

  1. quoteXML(String string)
  2. quoteXML(String string)
  3. quoteXML(String xmlFragment)
  4. quoteXmlContent(String x)
  5. quoteXMLValue(final Object o)