Update XML Document with JDOM2

In this tutorial we show how to update an XML Document using JDOM. We can modify the XML Document after we load it into memory. We show you how to do the following updates:

  • Edit an element/attribute.
  • Add an element/attribute
  • Remove an element/attribute

We are updating the following XML.

<?xml version="1.0" encoding="UTF-8"?>
    <course id="1" transient="false">
        <name>Update XML with JDOM</name>
    <course id="2">
        <name>Modify XML with JDOM</name>

Edit XML Document with JDOM

First, we need to load the XML document into memory. Next, we iterate over the children of the root element and we show how to edit, add and remove elements or attributes in the Document. Finally, we print the result to the console.

package com.memorynotfound.xml.jdom;

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

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class EditXmlJDom {

    public static void main(String... args) throws JDOMException, IOException {

        // parse and load file into memory
        InputStream in = EditXmlJDom.class.getResourceAsStream("/example.xml");
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(in);

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

        // iterating over the children
        List<Element> courses = root.getChildren("course");
        for (Element element : courses){
            Attribute id = element.getAttribute("id");

            if ("1".equals(id.getValue())){

                // edit attribute

                // add attribute
                Attribute selected = new Attribute("selected", "true");

                // remove attribute

            } else if ("2".equals(id.getValue())){

                // edit element

                // add element
                Element date = new Element("date").setText("2016-01-01");

                // remove element
        XMLOutputter xmlOutput = new XMLOutputter();

        // display xml
        xmlOutput.output(document, System.out);


<?xml version="1.0" encoding="UTF-8"?>
  <course id="10" selected="true">
    <name>Update XML with JDOM</name>
  <course id="2">



You may also like...