Quote a string so that it can be included as an XML attribute value. - Java XML

Java examples for XML:XML Attribute

Description

Quote a string so that it can be included as an XML attribute value.

Demo Code

/*//from  w  ww  .  ja v a  2s.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.
 */
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;

public class Main{
    /** Quote a string so that it can be included as an XML attribute value. */
    public static void printAtt(PrintWriter pw, String val) {
        pw.print("\"");
        pw.print(escapeForQuoting(val));
        pw.print("\"");
    }
    /** Print an XML attribute name and value for string val */
    public static void printAtt(PrintWriter pw, String name, String val) {
        if (val != null /* && !val.equals("") */) {
            pw.print(" ");
            pw.print(name);
            pw.print("=\"");
            pw.print(escapeForQuoting(val));
            pw.print("\"");
        }
    }
    /** Print an XML attribute name and value for int val */
    public static void printAtt(PrintWriter pw, String name, int val) {
        pw.print(" ");
        pw.print(name);
        pw.print("=\"");
        pw.print(val);
        pw.print("\"");
    }
    /** Print an XML attribute name and value for boolean val */
    public static void printAtt(PrintWriter pw, String name, boolean val) {
        pw.print(" ");
        pw.print(name);
        pw.print(val ? "=\"true\"" : "=\"false\"");
    }
    private static String escapeForQuoting(String val) {
        return StringEscaper.xmlNumericEscaper.escapeString(val);
    }
}

Related Tutorials