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

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

        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        try {
            outputter.output(doc, System.out);
        } catch (Exception 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>

Maven Dependencies

<!-- https://mvnrepository.com/artifact/org.jdom/jdom2 -->
<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6</version>
</dependency>

How do I create an XML document using JDOM?

In this small program you can see how to use JDOM to create a simple xml file. Below you’ll see how to create elements of the xml document, set some text for the element.

After that you can see how to use the XMLOutputter class to write the JDOM document into file and display it on the screen. To make the output better we can apply a Format to our xml document.

package org.kodejava.example.jdom;

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

import java.io.FileWriter;

public class JDomCreatingXml {
    public static void main(String[] args) {
        // <rows>
        //     <row>
        //         <firstname>Alice</firstname>
        //         <lastname>Starbuzz</lastname>
        //         <address>Sunset Road</address>
        //     </row>
        // </row>
        Document document = new Document();
        Element root = new Element("rows");

        // Creating a child for the root element. Here we can see how to
        // set the text of an xml element.
        Element child = new Element("row");
        child.addContent(new Element("firstname").setText("Alice"));
        child.addContent(new Element("lastname").setText("Starbuzz"));
        child.addContent(new Element("address").setText("Sunset Road"));

        // Add the child to the root element and add the root element as
        // the document content.
        root.addContent(child);
        document.setContent(root);

        try {
            FileWriter writer = new FileWriter("userinfo.xml");
            XMLOutputter outputter = new XMLOutputter();

            // Set the XLMOutputter to pretty formatter. This formatter
            // use the TextMode.TRIM, which mean it will remove the
            // trailing white-spaces of both side (left and right)
            outputter.setFormat(Format.getPrettyFormat());

            // Write the document to a file and also display it on the
            // screen through System.out.
            outputter.output(document, writer);
            outputter.output(document, System.out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

This program will output the following XML document:

<!-- https://mvnrepository.com/artifact/org.jdom/jdom2 -->
<?xml version="1.0" encoding="UTF-8"?>
<rows>
  <row>
    <firstname>Alice</firstname>
    <lastname>Starbuzz</lastname>
    <address>Sunset Road</address>
  </row>
</rows>

Maven Dependencies

<!-- https://mvnrepository.com/artifact/org.jdom/jdom2 -->
<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6</version>
</dependency>

How do I create a Document object in JDOM?

The following example show you how to create a simple Document object in JDOM. We can create a new document directly by creating a new instance of the Document class, for additional information we can pass an Element as an argument.

To create a Document from an existing XML file we can use the SAXBuilder. Beside reading from file we can also build a Document from stream and URL.

package org.kodejava.example.jdom;

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

import java.io.File;

public class JDOMCreateDocument {
    public static void main(String[] args) {
        // Creating a document with an Element as the parameter.
        Element element = new Element("root");
        element.setText("Hello World");

        Document document = new Document(element);
        System.out.println("root.getName() = " +
                document.getRootElement().getName());

        // We can also create a document from a file, stream or URL using
        // a SAXBuilder
        SAXBuilder builder = new SAXBuilder();
        try {
            // Build a document from a file using a SAXBuilder.
            // The content of data.xml file:
            //
            // <?xml version="1.0" encoding="UTF-8"?>
            // <data>
            //     <row>
            //         <username>alice</username>
            //         <password>secret</password>
            //     </row>
            // </data>
            document = builder.build(new File("data.xml"));
            Element root = document.getRootElement();
            System.out.println("root.getName() = " + root.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<!-- https://mvnrepository.com/artifact/org.jdom/jdom2 -->
<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6</version>
</dependency>

How do I read an XML document using JDOM?

This example provide a small code snippet on how to use JDOM to parse an XML document, iterates each of the element and read the element or attributes values. To play with this example you have to have the JDOM library. You can download it from JDOM website.

package org.kodejava.example.jdom;

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

import java.io.ByteArrayInputStream;
import java.util.List;

public class ReadXmlDocument {
    public static void main(String[] args) {
        // Our imaginary xml file to be processed in this example.
        String data = "<root>" +
                "<row>" +
                "<column name=\"username\" length=\"16\">admin</column>" +
                "<column name=\"password\" length=\"128\">secret</column>" +
                "</row>" +
                "<row>" +
                "<column name=\"username\" length=\"16\">jdoe</column>" +
                "<column name=\"password\" length=\"128\">password</column>" +
                "</row>" +
                "</root>";

        // Create an instance of SAXBuilder
        SAXBuilder builder = new SAXBuilder();
        try {
            // Tell the SAXBuilder to build the Document object from the
            // InputStream supplied.
            Document document = builder.build(
                    new ByteArrayInputStream(data.getBytes()));

            // Get our xml document root element which equals to the
            // <root> tag in the xml document.
            Element root = document.getRootElement();

            // Get all the children named with <row> in the document.
            // The method return the children as a java.util.List
            // object.
            List rows = root.getChildren("row");
            for (int i = 0; i < rows.size(); i++) {
                // Convert each row to an Element object and get its
                // children which will return a collection of <column>
                // elements. When we have to column element we can read
                // the attribute value (name, length) as defined above
                // and also read its value (between the <column></column>
                // tag) by calling the getText() method.
                //
                // The getAttribute() method also provide a handy method
                // if we want to convert the attribute value to a correct
                // org.kodejava.data type, in the example we read the length attribute
                // value as an integer.
                Element row = (Element) rows.get(i);
                List columns = row.getChildren("column");
                for (int j = 0; j < columns.size(); j++) {
                    Element column = (Element) columns.get(j);
                    String name = column.getAttribute("name").getValue();
                    String value = column.getText();
                    int length = column.getAttribute("length").getIntValue();

                    System.out.println("name = " + name);
                    System.out.println("value = " + value);
                    System.out.println("length = " + length);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<!-- https://mvnrepository.com/artifact/org.jdom/jdom2 -->
<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6</version>
</dependency>

Download