Example #1
0
  /**
   * Set attribute with given key, value pair. Figures out a quote character to use if necessary.
   *
   * @param key The name of the attribute.
   * @param value The value of the attribute.
   */
  public void setAttribute(String key, String value) {
    char ch;
    boolean needed;
    boolean singleq;
    boolean doubleq;
    String ref;
    StringBuffer buffer;
    char quote;
    Attribute attribute;

    // first determine if there's whitespace in the value
    // and while we'return at it find a suitable quote character
    needed = false;
    singleq = true;
    doubleq = true;
    if (null != value)
      for (int i = 0; i < value.length(); i++) {
        ch = value.charAt(i);
        if (Character.isWhitespace(ch)) needed = true;
        else if ('\'' == ch) singleq = false;
        else if ('"' == ch) doubleq = false;
      }

    // now apply quoting
    if (needed) {
      if (doubleq) quote = '"';
      else if (singleq) quote = '\'';
      else {
        // uh-oh, we need to convert some quotes into character references
        // convert all double quotes into &#34;
        quote = '"';
        ref = "&quot;"; // Translate.encode (quote);
        // JDK 1.4: value = value.replaceAll ("\"", ref);
        buffer = new StringBuffer(value.length() * 5);
        for (int i = 0; i < value.length(); i++) {
          ch = value.charAt(i);
          if (quote == ch) buffer.append(ref);
          else buffer.append(ch);
        }
        value = buffer.toString();
      }
    } else quote = 0;
    attribute = getAttributeEx(key);
    if (null != attribute) { // see if we can splice it in rather than replace it
      attribute.setValue(value);
      if (0 != quote) attribute.setQuote(quote);
    } else setAttribute(key, value, quote);
  }