Getting and Setting an Attribute in a DOM Element : Attribute « XML « Java Tutorial


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();
    Document doc = factory.newDocumentBuilder().parse(new File("filename"));

    Element element = doc.getElementById("key1");
    boolean has = element.hasAttribute("value"); 
    String attrValue = element.getAttribute("value"); 
    element.setAttribute("value", "newValue1");

    element = doc.getElementById("key2");
    has = element.hasAttribute("value"); 
    attrValue = element.getAttribute("value"); 

    element.setAttribute("value", "a<\"'&>z");


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