Share on Google+Share on Google+

Adding an Attribute in DOM Document

In this section, you will learn how to adds an attribute in a DOM document.

Adding an Attribute in DOM Document


This Example shows you how to adds an attribute in a DOM document. JAXP (Java API for XML Processing) is an interface which provides parsing of xml documents. Here the Document BuilderFactory is used to create new DOM parsers. There are some of the methods used in code given below for adding attribute:-

getDocumentElement():- allows direct access to the root node of the document.

root.getAttribute("Id"):-allows to retrieve attributes on  Id.
root.setAttribute("Id", "05MC34"):-allows to set o5Mc34 on the Id

Xml code for the program generated is:-

<?xml version="1.0" encoding="UTF-8"?>
<Author Type='Bible' Id='Rose-78' Issue='1995'>
</Author> :-


 * @Program that Adds an Attribute to an Element
 * Author:-RoseIndia Team
 * Date:-09-Jun-2008

import javax.xml.parsers.*;
import org.w3c.dom.*;

public class Addingattribute {

  public static void main(String[] argsthrows Exception {
  //boolean validating = false;
  DocumentBuilderFactory factory = 

  Document doc = factory.newDocumentBuilder().parse(
  new Addingattribute().addAttribute(doc);

  public void addAttribute(Document doc) {
  Element root = doc.getDocumentElement();
  System.out.print("Attributes of Id before Adding is: ");
  //Adds an attributes to the element ISBN
  System.out.print("Attributes of Id after Adding is: ");

Output of the program:-

Attributes of Id before Adding is: Rose-78
Attributes of Id after Adding is: 05MC34

Download Source Code



Posted on: August 24, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Adding an Attribute in DOM Document  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image