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

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

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

Leave a Reply