Java XML Encode xmlEncode(String s)

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

Description

XML encode a string.

License

Open Source License

Parameter

Parameter Description
s any String

Return

the String with &, <, and > encoded for use in XML.

Declaration

public static String xmlEncode(String s) 

Method Source Code

//package com.java2s;
/**/*from   w w  w .  j a va2  s  .com*/
 * Copyright 2006 OCLC Online Computer Library Center Licensed under the Apache
 * License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or
 * agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * XML encode a string.
     * @param s any String
     * @return the String with &amp;, &lt;, and &gt; encoded for use in XML.
     */
    public static String xmlEncode(String s) {
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < s.length(); ++i) {
            char c = s.charAt(i);
            switch (c) {
            case '&':
                sb.append("&amp;");
                break;
            case '<':
                sb.append("&lt;");
                break;
            case '>':
                sb.append("&gt;");
                break;
            case '"':
                sb.append("&quot;");
                break;
            case '\'':
                sb.append("&apos;");
                break;
            default:
                sb.append(c);
                break;
            }
        }
        return sb.toString();
    }
}

Related

  1. xmlEncode(final String text)
  2. XMLEncode(final String value)
  3. xmlEncode(String in)
  4. XMLEncode(String name)
  5. xmlEncode(String s)
  6. xmlEncode(String s)
  7. xmlEncode(String s)
  8. xmlEncode(String s)
  9. xmlEncode(String str)