How do I navigate the XML elements tree in JDOM?

package org.kodejava.jdom;

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

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.List;

public class JDOMTraversingElement {
    public static void main(String[] args) {
        String xml = """
                <root>
                    <country name="Japan" capital="Tokyo"/>
                    <country name="France" capital="Paris"/>
                    <country name="Italy" capital="Rome"/>
                    <country name="England" capital="London"/>
                    <country name="Indonesia" capital="Jakarta"/>
                    <city name="Denpasar"/>
                    <city name="Bangkok"/>
                    <city name="Mumbai"/>
                    <city name="Delhi"/>
                </root>""";

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

            // Getting the root element
            Element root = document.getRootElement();

            // Getting the first child
            Element country = root.getChild("country");
            System.out.println("Name: " + country.getAttribute("name")
                    .getValue());
            System.out.println("Capital: " + country.getAttribute("capital")
                    .getValue());
            System.out.println("----------------------------------------");

            // Getting all children of the root
            List<Element> elements = root.getChildren();
            for (Element element : elements) {
                if (element.getName().equals("country")) {
                    System.out.println(MessageFormat.format("{0} -> {1}",
                            element.getAttribute("name").getValue(),
                            element.getAttribute("capital").getValue()));
                } else if (element.getName().equals("city")) {
                    System.out.println(element.getAttribute("name")
                            .getValue());
                }
            }
            System.out.println("----------------------------------------");

            // Getting all children of the root named city
            List<Element> cities = root.getChildren("city");
            for (Element city : cities) {
                System.out.println(city.getAttribute("name").getValue());
            }
        } catch (JDOMException | IOException e) {
            e.printStackTrace();
        }
    }
}

The result of the code snippet are:

Name: Japan
Capital: Tokyo
----------------------------------------
Japan -> Tokyo
France -> Paris
Italy -> Rome
England -> London
Indonesia -> Jakarta
Denpasar
Bangkok
Mumbai
Delhi
----------------------------------------
Denpasar
Bangkok
Mumbai
Delhi

Maven Dependencies

<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6.1</version>
</dependency>

Maven Central

How do I remove an attribute from XML element in JDOM?

The following example shows you how to remove attributes from an XML element. We will remove attribute named userid from the <row> element. To remove an attribute you can call the removeAttribute(String name) method of the Element object.

package org.kodejava.jdom;

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

import java.io.File;

public class JDOMRemoveAttribute {
    public static void main(String[] args) {
        SAXBuilder builder = new SAXBuilder();
        try {
            // <?xml version="1.0" encoding="UTF-8"?>
            // <root>
            //     <row userid="alice">
            //         <firstname>Alice</firstname>
            //         <lastname>Starbuzz</lastname>
            //     </row>
            // </root>
            Document doc = builder.build(new File("data.xml"));
            XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
            out.output(doc, System.out);

            // Get the root element and find a child named row and remove
            // its attribute named "userid"
            Element root = doc.getRootElement();
            root.getChild("row").removeAttribute("userid");
            out.output(doc, System.out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The program will output the following result to the console:

<?xml version="1.0" encoding="UTF-8"?>
<data>
  <row>
    <username>alice</username>
    <password>secret</password>
  </row>
</data>
<?xml version="1.0" encoding="UTF-8"?>
<data>
  <row>
    <username>alice</username>
    <password>secret</password>
  </row>
</data>

Maven Dependencies

<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6.1</version>
</dependency>

Maven Central

How do I remove an element from XML document in JDOM?

This example show you how to remove an element from XML document. In the code snippet below we start by loading an XML document and display its original contents. After that we find the element <row>, and remove the <address> element from it. To get the first child we are using the getChild() method from the root Element object. To remove an element we use the removeChild() method.

package org.kodejava.jdom;

import org.jdom2.Document;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import java.io.File;

public class JDOMRemoveElement {
    public static void main(String[] args) {
        SAXBuilder builder = new SAXBuilder();
        try {
            Document doc = builder.build(new File("userinfo.xml"));

            // The lines below output the original userinfo.xml content
            //
            // <?xml version="1.0" encoding="UTF-8"?>
            // <rows>
            //   <row>
            //     <firstname>Alice</firstname>
            //     <lastname>Mallory</lastname>
            //     <address>Sunset Road</address>
            //   </row>
            // </rows>
            XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
            out.output(doc, System.out);

            // Remove the address element from Alice information. First we
            // get the row element from the root element, and finally 
            // remove the address from the row. And the result will be:
            //
            // <?xml version="1.0" encoding="UTF-8"?>
            // <rows>
            //   <row>
            //     <firstname>Alice</firstname>
            //     <lastname>Mallory</lastname>
            //   </row>
            // </rows>
            doc.getRootElement().getChild("row").removeChild("address");
            out.output(doc, System.out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The code snippet print the following output:

<?xml version="1.0" encoding="UTF-8"?>
<rows>
  <row>
    <firstname>Alice</firstname>
    <lastname>Starbuzz</lastname>
    <address>Sunset Road</address>
  </row>
</rows>
<?xml version="1.0" encoding="UTF-8"?>
<rows>
  <row>
    <firstname>Alice</firstname>
    <lastname>Starbuzz</lastname>
  </row>
</rows>

Maven Dependencies

<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6.1</version>
</dependency>

Maven Central

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.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

<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6.1</version>
</dependency>

Maven Central

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.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:

<?xml version="1.0" encoding="UTF-8"?>
<rows>
  <row>
    <firstname>Alice</firstname>
    <lastname>Starbuzz</lastname>
    <address>Sunset Road</address>
  </row>
</rows>

Maven Dependencies

<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6.1</version>
</dependency>

Maven Central