Java XML Encode xmlEncode(String s)

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

Description

Convert given string in XML friendly version.

License

Open Source License

Parameter

Parameter Description
s string to xml encode

Return

xml encoded version of s.

Declaration

public static String xmlEncode(String s) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010 - 2013 Danny Katzel.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html/*w ww .  j  av  a2  s  .  co  m*/
 * 
 * Contributors:
 *     Danny Katzel - initial API and implementation
 ******************************************************************************/

public class Main {
    /**
     * Convert given string in XML friendly version.
     * This method will replace {@code < > and &} into
     * {@code &#} equivalents.
     * @param s string to xml encode
     * @return xml encoded version of s.
     */
    public static String xmlEncode(String s) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '<' || c == '>' || c == '&') {
                builder.append("&#" + (int) c + ";");
            } else {
                builder.append(c);
            }
        }
        return builder.toString();
    }
}

Related

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