How do I add attributes to an XML elements in JDOM?

The program below will show you how to add attributes to an XML elements. Using JDOM library this can be easily done by calling the Element‘s setAttribute(String name, String value) method.

package org.kodejava.example.jdom;

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

public class JDOMAddAttribute {
    public static void main(String[] args) {
        Document doc = new Document();
        Element root = new Element("root");

        // Create <row userid="alice"></row>
        Element child = new Element("row").setAttribute("userid", "alice");

        // Create <name firstname="Alice" lastname="Starbuzz"></name>
        Element name = new Element("name")
                .setAttribute("firstname", "Alice")
                .setAttribute("lastname", "Starbuzz");


        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        try {
            outputter.output(doc, System.out);
        } catch (Exception e) {

And here goes the output:

<?xml version="1.0" encoding="UTF-8"?>
  <row userid="alice">
    <name firstname="Alice" lastname="Starbuzz" />

Maven Dependencies

<!-- -->

Maven Central

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.