java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to add attributes to an XML elements?

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 com.javacoderanch.example.jdom;

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


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 (IOException e) {

And here goes the output:

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