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>
Latest posts by Wayan (see all)
- How do I use Proxy class to configure HTTP and SOCKS proxies in Java? - March 27, 2025
- How do I retrieve network interface information using NetworkInterface in Java? - March 26, 2025
- How do I work with InetAddress to resolve IP addresses in Java? - March 25, 2025