Encode a String for XML output, displaying it to a PrintWriter. - Java XML

Java examples for XML:XML Encoding

Description

Encode a String for XML output, displaying it to a PrintWriter.

Demo Code

/*//from   www.ja  v a 2 s.  c  om
// Licensed to Julian Hyde under one or more contributor license
// agreements. See the NOTICE file distributed with this work for
// additional information regarding copyright ownership.
//
// Julian Hyde licenses this file to you 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.
 */
//package com.java2s;

import java.io.PrintWriter;

public class Main {
    /**
     * Encode a String for XML output, displaying it to a PrintWriter.
     * The String to be encoded is displayed, except that
     * special characters are converted into entities.
     * @param input a String to convert.
     * @param out a PrintWriter to which to write the results.
     */
    public static void stringEncodeXML(String input, PrintWriter out) {
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            switch (c) {
            case '<':
            case '>':
            case '"':
            case '\'':
            case '&':
            case '\t':
            case '\n':
            case '\r':
                out.print("&#" + (int) c + ";");
                break;
            default:
                out.print(c);
            }
        }
    }
}

Related Tutorials