Home Tutorial Xml Jdom JDOM Element Example, How to set attribute of xml element in java.

 
 

Share on Google+Share on Google+
JDOM Element Example, How to set attribute of xml element in java.
Posted on: August 19, 2010 at 12:00 AM
Advertisement
In this tutorial, you will see how to set attribute of xml element in java.

JDOM Element Example, How to set attribute of xml element in java.

In this tutorial, we will see how to set attribute of xml element in java with the help of
JDOM library. JDOM is used for parsing, creating, manipulating, and serializing XML
documents.

In this example, we will use some methods. DOMBuilder is a class that build a
JDOMDocument of xml file. The getRootElement method of Document class is
 used for accessing  root element. The setAttribute(String name, String value)
method set a attribute of an element with given name and value. The Element class
 is available in org.jdom.Element pacakage.

Element API.

Return Type Method Description
Element setAttribute(String name, String value) The setAttribute(.....) method set attribute of element.

Code:

student.xml

<?xml version="1.0"?>
<Student >
  <info id="1"  >
    <first name="bharat">bly </first>
      </info>
  <info  id="2">
    <first name="ankit" >lko</first>    
  </info>
  <info id="3" >
    <first name="gyan">bly</first>
    </info>
</Student>

CloneAttribute.java

package roseindia;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.DOMBuilder;
import java.io.File;

public class SetAttribute {
  public static void main(String[] args) {
    try {
      String data = "student.xml";
      File file = new File(data);
      DOMBuilder builder = new DOMBuilder(false);
      Document doc = builder.build(file);
      Element root = doc.getRootElement();
      System.out.println("Root Element" + root);
      Element att = root.setAttribute("id""001");
      Attribute attribute = att.getAttribute("id");
      System.out.println("Atttribute : " + attribute);
    catch (Exception e) {
      System.out.println("Execption " + e.getMessage());
    }
  }
}

Output:

Root Element[Element: <Student/>]
Atttribute : [Attribute: id="001"]

Download this code

Advertisement

Related Tags for JDOM Element Example, How to set attribute of xml element in java.:


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.

Posted on: August 19, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com