Add attribute to an element in Java

Description

The following code shows how to add attribute to an element.

Example


 // w  w w . j a  v  a 2s  . com
import javax.xml.parsers.DocumentBuilder;
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();
    DocumentBuilder loader = factory.newDocumentBuilder();

    Document document = loader.newDocument();
    Element root = document.createElement("order");
    root.setAttribute("src", "java2s.com");
    document.appendChild(root);
    System.out.println(root +" "+ root.getAttribute("src"));
    System.out.println(document);
  }

}

The code above generates the following result.





















Home »
  Java Tutorial »
    XML »




DOM
SAX