Header javaperspective.com
JavaPerspective.com  >   Advanced Tutorials  >   3. XML processing with JDOM  >   3.11. Working with attributes

3.11. Working with attributes
Last updated: 2 January 2013.

This tutorial will show you how to use attributes with the JDOM library.

The class Element provides methods you can use to set attributes to an element, retrieve the attributes of an element, remove the attributes of an element and also move the attributes from one element to another.

As an example, there are no attributes in the file hotel.xml shown below:

   <?xml version="1.0"?>
   <HOTEL>
            <ROOM>
                     <NUMBER>17</NUMBER>
                     <CATEGORY>STANDARD</CATEGORY>
                     <BED>DOUBLE SIZE</BED>
                     <FLOOR>5</FLOOR>
                     <LIVING_ROOM/>
                     <KITCHENETTE/>
                     <AIR_CONDITIONING>
                              <TABLE_FANS>2</TABLE_FANS>
                     </AIR_CONDITIONING>
            </ROOM>
            <ROOM>
                     <NUMBER>33</NUMBER>
                     <CATEGORY>SUITE</CATEGORY>
                     <BED>DOUBLE SIZE</BED>
                     <BED>KING SIZE</BED>
                     <FLOOR>9</FLOOR>
                     <LIVING_ROOM>17 FEET * 13 FEET</LIVING_ROOM>
                     <KITCHENETTE>10 FEET * 8 FEET</KITCHENETTE>
                     <JACUZZI>3 SEATS</JACUZZI>
                     <AIR_CONDITIONING>
                              <AIR_CONDITIONERS>5</AIR_CONDITIONERS>
                     </AIR_CONDITIONING>
            </ROOM>
   </HOTEL>

Let's add attributes to the root element HOTEL by calling the method setAttribute provided by the class Element. Here is the code:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;


public final class JDOMDemo {


   
private void addAttributes(){
         
BufferedWriter writer = null;

         
try {
               
// Read the XML file and get a JDOM document
               
SAXBuilder builder = new SAXBuilder();
                Document document = builder.build
(new File("hotel.xml"));

               
// Get the root element
               
Element rootElement = document.getRootElement();

               
// Set the root element's attributes
               
rootElement.setAttribute("name", "Seasons Hotel");
                rootElement.setAttribute
("starRating", "3");

               
// Create a BufferedWriter object
               
writer = new BufferedWriter(new FileWriter("hotelWithAttributes.xml"));

               
// Output the JDOM document to the BufferedWriter object
               
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
                outputter.output
(document, writer);
         
}
         
catch (Exception e) {
               
e.printStackTrace();
         
}
         
finally{
               
if(writer != null){
                     
try {
                           
writer.close();
                     
}
                     
catch (IOException e) {
                           
e.printStackTrace();
                     
}
                }
          }
    }


   
public static void main(String[] args){
         
new JDOMDemo().addAttributes();
   
}

}

The code above adds attributes to the root element HOTEL and outputs the JDOM document to the file hotelWithAttributes.xml. Here it is:

   <?xml version="1.0" encoding="UTF-8"?>
   <HOTEL name="Seasons Hotel" starRating="3">
            <ROOM>
                     <NUMBER>17</NUMBER>
                     <CATEGORY>STANDARD</CATEGORY>
                     <BED>DOUBLE SIZE</BED>
                     <FLOOR>5</FLOOR>
                     <LIVING_ROOM/>
                     <KITCHENETTE/>
                     <AIR_CONDITIONING>
                              <TABLE_FANS>2</TABLE_FANS>
                     </AIR_CONDITIONING>
                     <JACUZZI>3 SEATS</JACUZZI>
            </ROOM>
            <ROOM>
                     <NUMBER>33</NUMBER>
                     <CATEGORY>SUITE</CATEGORY>
                     <BED>DOUBLE SIZE</BED>
                     <BED>KING SIZE</BED>
                     <FLOOR>9</FLOOR>
                     <LIVING_ROOM>17 FEET * 13 FEET</LIVING_ROOM>
                     <KITCHENETTE>10 FEET * 8 FEET</KITCHENETTE>
                     <AIR_CONDITIONING>
                              <AIR_CONDITIONERS>5</AIR_CONDITIONERS>
                     </AIR_CONDITIONING>
            </ROOM>
   </HOTEL>

To retrieve a given attribute or the list of attributes bound to an element, use one of the methods getAttribute, getAttributes or getAttributeValue provided by the class ELEMENT. The methods getAttributeValue return the attribute's value as a String object whereas the methods getAttribute and getAttributes return an Attribute object. The class Attribute provides the following methods you can use to retrieve the value of an attribute according to its type: getBooleanValue, getDoubleValue, getFloatValue, getIntValue and getLongValue. For example, the code below retrieves the value of the attribute starRating in the form of an integer:

import java.io.File;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;


public final class JDOMDemo {


   
private void retrieveAttribute(){
         
try {
               
// Read the XML file and get a JDOM document
               
SAXBuilder builder = new SAXBuilder();
                Document document = builder.build
(new File("hotelWithAttributes.xml"));

               
// Get the root element
               
Element rootElement = document.getRootElement();

               
// Retrieve the integer value of the attribute starRating
               
Attribute attribute = rootElement.getAttribute("starRating");
               
int intValue = attribute.getIntValue();

               
// Do something with intValue
                // ...
         
}
         
catch (Exception e) {
               
e.printStackTrace();
         
}
    }


   
public static void main(String[] args){
         
new JDOMDemo().retrieveAttribute();
   
}

}

To remove attributes individually, use one of the methods removeAttribute provided by the class Element. If you want to remove all the attributes of an element, call the method getAttributes which returns the complete list of attributes and then call the method clear on the list. As an illustration, the code below removes all the attributes of the root element:

import java.io.File;
import java.util.List;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;


public final class JDOMDemo {


   
private void removeAttributes(){
         
try {
               
// Read the XML file and get a JDOM document
               
SAXBuilder builder = new SAXBuilder();
                Document document = builder.build
(new File("hotelWithAttributes.xml"));

               
// Get the root element
               
Element rootElement = document.getRootElement();

               
// Retrieve the list of attributes and call the method "clear" upon it
               
List<Attribute> attributes = rootElement.getAttributes();
                attributes.clear
();

               
// Output the JDOM document to the standard output
               
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
                outputter.output
(document, System.out);
         
}
         
catch (Exception e) {
               
e.printStackTrace();
         
}
    }


   
public static void main(String[] args){
         
new JDOMDemo().removeAttributes();
   
}

}

You can move an attribute from one element to another. First, call the method detach on the Attribute object and then call the method setAttribute on the Element object on which you want to move the attribute. Although it does not really make sense, suppose that you want to move the attribute starRating from the element HOTEL to the element TABLE_FANS. The code follows:

import java.io.File;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;


public final class JDOMDemo {


   
private void moveAttribute(){

         
try {
               
// Read the XML file and get a JDOM document
               
SAXBuilder builder = new SAXBuilder();
                Document document = builder.build
(new File("hotelWithAttributes.xml"));

               
// Get the root element
               
Element rootElement = document.getRootElement();

               
// Retrieve the attribute "starRating" and call the method "detach" upon it
               
Attribute starRatingAttribute = rootElement.getAttribute("starRating");
                starRatingAttribute.detach
();

               
// Get the element TABLE_FANS and set the attribute "starRating"
               
Element tableFansElement = rootElement.getChildren().get(0).getChild("AIR_CONDITIONING").getChild("TABLE_FANS");
                tableFansElement.setAttribute
(starRatingAttribute);

               
// Output the JDOM document to the standard output
               
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
                outputter.output
(document, System.out);
         
}
         
catch (Exception e) {
               
e.printStackTrace();
         
}
    }


   
public static void main(String[] args){
         
new JDOMDemo().moveAttribute();
   
}

}

The output is:

   <?xml version="1.0" encoding="UTF-8"?>
   <HOTEL name="Seasons Hotel">
            <ROOM>
                     <NUMBER>17</NUMBER>
                     <CATEGORY>STANDARD</CATEGORY>
                     <BED>DOUBLE SIZE</BED>
                     <FLOOR>5</FLOOR>
                     <LIVING_ROOM/>
                     <KITCHENETTE/>
                     <AIR_CONDITIONING>
                              <TABLE_FANS starRating="3">2</TABLE_FANS>
                     </AIR_CONDITIONING>
                     <JACUZZI>3 SEATS</JACUZZI>
            </ROOM>
            <ROOM>
                     <NUMBER>33</NUMBER>
                     <CATEGORY>SUITE</CATEGORY>
                     <BED>DOUBLE SIZE</BED>
                     <BED>KING SIZE</BED>
                     <FLOOR>9</FLOOR>
                     <LIVING_ROOM>17 FEET * 13 FEET</LIVING_ROOM>
                     <KITCHENETTE>10 FEET * 8 FEET</KITCHENETTE>
                     <AIR_CONDITIONING>
                              <AIR_CONDITIONERS>5</AIR_CONDITIONERS>
                     </AIR_CONDITIONING>
            </ROOM>
   </HOTEL>


You are here :  JavaPerspective.com  >   Advanced Tutorials  >   3. XML processing with JDOM  >   3.11. Working with attributes
Next tutorial :  JavaPerspective.com  >   Advanced Tutorials  >   3. XML processing with JDOM  >   3.12. Working with comments

Copyright © 2013 - 2016. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7