JDOM Attribute Example, How to convert value of attribute in different data type


 

JDOM Attribute Example, How to convert value of attribute in different data type

In this tutorial, you will see how to convert value of attribute in different data type.

In this tutorial, you will see how to convert value of attribute in different data type.

JDOM Attribute Example, How to convert value of attribute
in different data type

In this tutorial, we will see how to retrieve the value of an attribute in different data type like int, float, boolean etc with the help of JDOM library.

The JDOM libraries allows you to modify the value of node attribute in runtime. This examples shows how to set the value of node element. Here we are using org.jdom.Attribute class from the JDOM library.

The getValue()  method of the org.jdom.Attribute class returns the text value of the attribute. This class is also providing other methods to get the values in the int, long, float etc. These methods try to convert the value in required format, if there is some data conversion error, it throws the DataConversionException exception.

Here is the xml file used in this example.

student.xml

<?xml version="1.0"?>
<Student >
    <first name="bharat" id="10">
    <city>Bly</city>
     </first>
    <first name="ankit" id="20" >
    <city>lko</city>
    </first>
    <first name="gyan" id="30">
    <city>lko</city>
    </first>
</Student>

AttrDiffTypeValue .java

package roseindia;

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

public class AttrDiffTypeValue {
  static String data = "student.xml";
  static File file = new File(data);
  static DOMBuilder builder = new DOMBuilder();

  public static void main(String[] args) {
    try {
      Document doc = builder.build(file);
      Element rootEl = doc.getRootElement();
      Element attElement = rootEl.setAttribute("id""5677");
      Attribute attribute = attElement.getAttribute("id");
      String str = attribute.getValue();
      System.out.println("Actual value of attribute : " + str);
      int intValue = attribute.getIntValue();
      System.out.println("Int value of attribute : " + intValue);
      double doubValue = attribute.getDoubleValue();
      System.out.println("Double value of attribute : " + doubValue);
      boolean bool = attribute.getBooleanValue();
      System.out.println("Int value of attribute : " + bool);
    catch (DataConversionException dex) {
      System.out.println(dex);
    catch (Exception ex) {
      System.out.println("Execption " + ex);
    }
  }
}

Output:

Actual value of attribute : 5677
Int value of attribute : 5677
Double value of attribute : 5677.0
org.jdom.DataConversionException

Download this code

Ads