Getting and Setting an Attribute in a DOM Element - Java XML

Java examples for XML:XML Attribute

Description

Getting and Setting an Attribute in a DOM Element

Demo Code

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


public class Main {
  public static void main(String[] argv) {
    Document doc = null;//from   www  .  j  ava  2s. co  m

    Element element = doc.getElementById("key1");

    // Determine the presence of an attribute
    boolean has = element.hasAttribute("value"); // true

    // Get an attribute value; returns null if not present
    String attrValue = element.getAttribute("value"); // value1

    // Change the value of an attribute
    element.setAttribute("value", "newValue1");

    // If an attribute is not specified in the XML but has a
    // default value, the attribute is automatically created
    element = doc.getElementById("key2");
    has = element.hasAttribute("value"); // true
    attrValue = element.getAttribute("value"); // value2

    // If the attribute value contains special characters,
    // they are converted to entities when the
    // document in dumped
    element.setAttribute("value", "a<\"'&>z");
  }
}

Related Tutorials