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

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.