Adding and Removing an Attribute in a DOM Element - Java XML

Java examples for XML:XML Attribute

Description

Adding and Removing an Attribute in a DOM Element

Demo Code


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

public class Main {
  public void main() {
    // Obtain an element; this method is implemented in
    Document doc = null;//parseXmlFile("infilename.xml", true);
    Element element = doc.getElementById("key1");

    // Add an attribute
    element.setAttribute("newAttrName", "attrValue");

    element.setAttribute("newAttrName", "<>&\"'");

    // Remove an attribute
    element.removeAttribute("value");

    boolean has = element.hasAttribute("value"); // true

    String attrValue = element.getAttribute("value"); // mydefault
  }//from www. ja  va  2s.c o m
}

Related Tutorials