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 create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023