Update XML Document with JDOM2
In this tutorial we show how to update an XML Document using JDOM. We can modify the XML Document after we load it into memory. We show you how to do the following updates:
- Edit an element/attribute.
- Add an element/attribute
- Remove an element/attribute
We are updating the following XML.
<?xml version="1.0" encoding="UTF-8"?>
<courses>
<course id="1" transient="false">
<name>Update XML with JDOM</name>
<price>0.0</price>
</course>
<course id="2">
<name>Modify XML with JDOM</name>
<price>0.0</price>
</course>
</courses>
Edit XML Document with JDOM
First, we need to load the XML document into memory. Next, we iterate over the children of the root element and we show how to edit, add and remove elements or attributes in the Document. Finally, we print the result to the console.
package com.memorynotfound.xml.jdom;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class EditXmlJDom {
public static void main(String... args) throws JDOMException, IOException {
// parse and load file into memory
InputStream in = EditXmlJDom.class.getResourceAsStream("/example.xml");
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(in);
// getting the root element
Element root = document.getRootElement();
// iterating over the children
List<Element> courses = root.getChildren("course");
for (Element element : courses){
Attribute id = element.getAttribute("id");
if ("1".equals(id.getValue())){
// edit attribute
id.setValue("10");
// add attribute
Attribute selected = new Attribute("selected", "true");
element.setAttribute(selected);
// remove attribute
element.removeAttribute("transient");
} else if ("2".equals(id.getValue())){
// edit element
element.getChild("price").setText("99.99");
// add element
Element date = new Element("date").setText("2016-01-01");
element.addContent(date);
// remove element
element.removeChild("name");
}
}
XMLOutputter xmlOutput = new XMLOutputter();
// display xml
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(document, System.out);
}
}
Output:
<?xml version="1.0" encoding="UTF-8"?>
<courses>
<course id="10" selected="true">
<name>Update XML with JDOM</name>
<price>0.0</price>
</course>
<course id="2">
<price>99.99</price>
<date>2016-01-01</date>
</course>
</courses>