java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to get xml attribute as an integer value?

In this example you can see how we can read the xml attribute value as an integer value instead of string. JDOM provides method such as getIntValue(), getLongValue(), getFloatValue(), getDoubleValue() to get numerical values. For boolean value we can use the getBooleanValue() method.

package com.javacoderanch.example.jdom;

import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import java.io.StringReader;
import java.io.IOException;

public class JDOMIntegerAttributeValue {
    public static void main(String[] args) {
        String xml = "<root><table width="100"/></root>";

        SAXBuilder builder = new SAXBuilder();
        try {
            Document document = builder.build(new StringReader(xml));

            Element child = document.getRootElement().getChild("table");
            int tableWidth = child.getAttribute("width").getIntValue();
            System.out.println("tableWidth = " + tableWidth);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}