The following example shows you how to remove attributes from an XML element. We will remove attribute named userid
from the <row>
element. To remove an attribute you can call the removeAttribute(String name)
method of the Element
object.
package org.kodejava.jdom;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import java.io.File;
public class JDOMRemoveAttribute {
public static void main(String[] args) {
SAXBuilder builder = new SAXBuilder();
try {
// <?xml version="1.0" encoding="UTF-8"?>
// <root>
// <row userid="alice">
// <firstname>Alice</firstname>
// <lastname>Starbuzz</lastname>
// </row>
// </root>
Document doc = builder.build(new File("data.xml"));
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
out.output(doc, System.out);
// Get the root element and find a child named row and remove
// its attribute named "userid"
Element root = doc.getRootElement();
root.getChild("row").removeAttribute("userid");
out.output(doc, System.out);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The program will output the following result to the console:
<?xml version="1.0" encoding="UTF-8"?>
<data>
<row>
<username>alice</username>
<password>secret</password>
</row>
</data>
<?xml version="1.0" encoding="UTF-8"?>
<data>
<row>
<username>alice</username>
<password>secret</password>
</row>
</data>
Maven Dependencies
<!-- https://search.maven.org/remotecontent?filepath=org/jdom/jdom2/2.0.6.1/jdom2-2.0.6.1.jar -->
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.6.1</version>
</dependency>
Latest posts by Wayan (see all)
- How do I find Java version? - March 21, 2022
- How do I convert CSV to JSON string using Jackson? - February 13, 2022
- How do I convert CSV file to or from JSON file? - February 13, 2022