/** *
* This sets an attribute value for this element. Any existing attribute * with the same name and namespace URI is removed. *
* * @param attributeAttribute
to set
* @return this element modified
* @throws IllegalAddException if the attribute being added already has a
* parent or if the attribute namespace prefix collides with another
* namespace prefix on the element.
*/
public Element setAttribute(Attribute attribute) {
if (attribute.getParent() != null) {
throw new IllegalAddException(this, attribute,
"The attribute already has an existing parent \"" +
attribute.getParent().getQualifiedName() + "\"");
}
// Performance optimizing flag to help determine if we need to
// bother removing an old attribute
boolean preExisting = false;
// Verify the attribute's namespace prefix doesn't collide with
// another attribute prefix or this element's prefix.
// This is unfortunately pretty heavyweight but we don't need to do it
// for attributes without a namespace, and a little testing shows no
// real difference in build times anyway.
String prefix = attribute.getNamespace().getPrefix();
if (!prefix.equals("")) {
String uri = attribute.getNamespace().getURI();
if (prefix.equals(getNamespacePrefix()) &&
!uri.equals(getNamespaceURI())) {
throw new IllegalAddException(this, attribute,
"The attribute namespace prefix \"" + prefix +
"\" collides with the element namespace prefix");
}
if (additionalNamespaces != null && additionalNamespaces.size() > 0) {
Iterator itr = additionalNamespaces.iterator();
while (itr.hasNext()) {
Namespace ns = (Namespace) itr.next();
if (prefix.equals(ns.getPrefix()) &&
!uri.equals(ns.getURI())) {
throw new IllegalAddException(this, attribute,
"The attribute namespace prefix \"" + prefix +
"\" collides with a namespace declared by the element");
}
}
}
if (attributes != null && attributes.size() > 0) {
Iterator itr = attributes.iterator();
while (itr.hasNext()) {
Attribute att = (Attribute)itr.next();
Namespace ns = att.getNamespace();
// Keep track if we have an existing attribute
if (attribute.getName().equals(att.getName()) &&
ns.getURI().equals(att.getNamespaceURI())) {
preExisting = true;
}
if (prefix.equals(ns.getPrefix()) &&
!uri.equals(ns.getURI())) {
throw new IllegalAddException(this, attribute,
"The attribute namespace prefix \"" + prefix +
"\" collides with another attribute namespace on " +
"the element");
}
}
}
}
else{
if (attributes != null && attributes.size() > 0) {
Iterator itr = attributes.iterator();
while (itr.hasNext()) {
Attribute att = (Attribute)itr.next();
// Keep track if we have an existing attribute
if (attribute.getName().equals(att.getName())) {
preExisting = true;
break;
}
}
}
}
if (attributes == null) {
attributes = new ArrayList(INITIAL_ARRAY_SIZE);
}
else if (preExisting) {
// Remove any pre-existing attribute
removeAttribute(attribute.getName(), attribute.getNamespace());
}
attributes.add(attribute);
attribute.setParent(this);
return this;
}