Adding and Removing an Attribute in a DOM Element : Attribute « XML « Java Tutorial






import java.io.File;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {
  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setExpandEntityReferences(false);
    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
    Element element = doc.getElementById("key1");

    element.setAttribute("newAttrName", "attrValue");
    element.setAttribute("newAttrName", "<>&\"'");
    element.removeAttribute("value");
    boolean has = element.hasAttribute("value"); // true
    String attrValue = element.getAttribute("value"); // mydefault
  }
}








33.22.Attribute
33.22.1.Adding and Removing an Attribute in a DOM Element
33.22.2.Listing All the Attributes of a DOM Element
33.22.3.Removing All the Attributes in a DOM Element
33.22.4.Remove all attributes by first making a copy of the attribute names and then using the list to remove the attributes:
33.22.5.Determining If an Attribute Was Supplied in a DOM Element
33.22.6.Accessing attributes of an element
33.22.7.Getting and Setting an Attribute in a DOM Element
33.22.8.Extracting attribute values from XML elements