Makes a tag string readable when rendered in HTML. - Java java.lang

Java examples for java.lang:String HTML

Description

Makes a tag string readable when rendered in HTML.

Demo Code

/*---------------------------------------------------------------
 *  Copyright 2005 by the Radiological Society of North America
 *
 *  This source software is released under the terms of the
 *  RSNA Public License (http://mirc.rsna.org/rsnapubliclicense)
 *----------------------------------------------------------------*/


//package com.java2s;
import java.io.StringWriter;

public class Main {


    /**/* w w  w . j  a v  a 2s.  c o  m*/
     * Makes a tag string readable when rendered in HTML. The method
     * escapes all the angle brackets and inserts spaces before and
     * after tags so a browser will wrap the text correctly.
     * This method is used in many places to return an XML string to the
     * user in the event of an error.
     * @param tagString the string containing XML tags.
     * @return the readable tag string, or "null" if tagString is null.
     */
    public static String makeReadableTagString(String tagString) {
        if (tagString == null)
            return "null";
        StringWriter sw = new StringWriter();
        char c;
        for (int i = 0; i < tagString.length(); i++) {
            c = tagString.charAt(i);
            if (c == '<')
                sw.write(" &#60;"); //note the leading space
            else if (c == '>')
                sw.write("&#62; "); //note the trailing space
            else if (c == '&')
                sw.write("&#38;");
            else if (c == '\"')
                sw.write("&#34;");
            else
                sw.write(c);
        }
        return sw.toString();
    }
}

Related Tutorials