Return a XML attribute setting. - Java XML

Java examples for XML:XML Attribute

Description

Return a XML attribute setting.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String name = "java2s.com";
        String value = "java2s.com";
        System.out.println(toAttribute(name, value));
    }/*www .j  a v a 2 s .  com*/

    /**
     * Return an attribute setting.
     * @param name the name of the attribute.
     * @param value the value of the attribute.
     * @return the encoded attribute = value string.
     */
    public static String toAttribute(String name, String value) {
        return " " + name + "=\"" + escapeAttribute(value) + "\"";
    }

    /**
     * Return an attribute setting.
     * @param name the name of the attribute.
     * @param value the value of the attribute.
     * @return the encoded attribute = value string.
     */
    public static String toAttribute(String name, int value) {
        return " " + name + "=\"" + value + "\"";
    }

    /**
     * Encode an attribute value.
     * This assumes use of " as the attribute value delimiter.
     * @param str the string to convert.
     * @return the converted string.
     */
    public static String escapeAttribute(String str) {
        final StringBuilder b = new StringBuilder();
        final char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; ++i) {
            final char c = chars[i];
            switch (c) {
            case '<':
                b.append("&lt;");
                break;
            case '>':
                b.append("&gt;");
                break;
            case '&':
                b.append("&amp;");
                break;
            case '"':
                b.append("&quot;");
                break;
            default:
                b.append(c);
            }
        }
        return b.toString();
    }
}

Related Tutorials