How do I add attributes to an XML elements?

Category: org.jdom, viewed: 1115 time(s).

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.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
import org.jdom.output.Format;

import java.io.IOException;

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");

        child.addContent(name);
        root.addContent(child);
        doc.addContent(root);

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

And here goes the output:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <row userid="alice">
    <name firstname="Alice" lastname="Starbuzz" />
  </row>
</root>
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats