JDOM Attribute Example, How to create clone of attribute in java.


 

JDOM Attribute Example, How to create clone of attribute in java.

In this tutorial, you will see how to create clone of attribute in java.

In this tutorial, you will see how to create clone of attribute in java.

JDOM Attribute Example, How to create clone of attribute in java.

In this tutorial, we will see how to create a clone of attribute in java by using JDOM library.
JDOM
is used for parsing, creating, manipulating, and serializing XML documents, it is
 a tree based Java api

In this example, we use few method  for creating clone of attribute. DOMBuilder is a class
 that build a JDOMDocument of xml file. The getRootElement method of Document class
 is used for accessing  root element. The getAttribute method returns attribute of element.
The clone method returns clone of attribute. The Attribute class is available in
org.jdom.Attribute pacakage.

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

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

public class CloneAttrbute {
  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();
      List row = root.getChildren("info");
      for (int i = 0; i < row.size(); i++) {
        Element infoElenemt = (Elementrow.get(i);
        List column = infoElenemt.getChildren("first");
        for (int j = 0; j < column.size(); j++) {
          Element student = (Elementcolumn.get(j);
          String attribute = student.getAttribute("name").getValue();
          Attribute clonAttribute = (Attributestudent.getAttribute(
          "name").clone();
          System.out.println("Attribute Value : " + attribute);
          System.out.println("Clone of attribute : " + clonAttribute);
        }
      }
    catch (Exception e) {
      System.out.println("Execption " + e.getMessage());
    }
  }
}

Output.

Attribute Value : bharat
Clone of attribute : [Attribute: name="bharat"] Attribute Value : ankit
Clone of attribute : [Attribute: name="ankit"]
Attribute Value : gyan
Clone of attribute : [Attribute: name="gyan"]

Download this code

Ads