Android XML String Escape escapeText(String rawText)

Here you can find the source of escapeText(String rawText)

Description

Escapes an XML string (i.e.

Declaration

public static String escapeText(String rawText) 

Method Source Code

//package com.java2s;

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

public class Main {
    /**/*from  w w  w  .  ja v a2  s .  c  om*/
     * Escapes an XML string (i.e. <br/>
     * becomes &lt;br/&gt;) There are 5 entities of interest (<, >, ", ', and &)
     *
     * Unfortunately there are no built-in Java utilities for this, so we had to roll our own
     */
    public static String escapeText(String rawText) {
        StringBuilder escapedText = new StringBuilder();
        StringCharacterIterator characterIterator = new StringCharacterIterator(
                rawText);
        char currentCharacter = characterIterator.current();
        while (currentCharacter != CharacterIterator.DONE) {
            switch (currentCharacter) {
            case '<':
                escapedText.append("&lt;");
                break;

            case '>':
                escapedText.append("&gt;");
                break;

            case '"':
                escapedText.append("&quot;");
                break;

            case '\'':
                escapedText.append("&apos;");
                break;

            case '&':
                escapedText.append("&amp;");
                break;

            default:
                escapedText.append(currentCharacter);
                break;
            }
            currentCharacter = characterIterator.next();
        }
        return escapedText.toString();
    }
}

Related

  1. toXMLString(String s)
  2. xmlEscape(String xml)
  3. escape(String input)
  4. getXmlEncoded(String text)
  5. encodeEntities(String content)
  6. encodeEntities(String content)
  7. encodeXML(final String str)