JDOM Edit XML File Example

Filed Under: Java

JDOM provides very neat way to manipulate XML files, using JDOM is very easy and the code looks clean and readable. Earlier we saw how to read XML using JDOM and how to write XML using JDOM. Here we will learn how easily we can edit XML files using JDOM.

JDOM Edit XML File

For this tutorial, we have following employees.xml file.


<?xml version="1.0" encoding="UTF-8"?>
<Employees xmlns="https://www.journaldev.com/employees">
  <Employee id="1">
    <age>25</age>
    <name>Pankaj</name>
    <gender>Male</gender>
    <role>Java Developer</role>
  </Employee>
  <Employee id="2">
    <age>34</age>
    <name>Mona</name>
    <gender>Female</gender>
    <role>Manager</role>
  </Employee>
  <Employee id="3">
    <age>45</age>
    <name>Dave</name>
    <gender>Male</gender>
    <role>Support</role>
  </Employee>
</Employees>

We want to change following for every Employee element in the XML.

  1. Update all name element to block letters.
  2. Append M for Male and F for Female in ID attribute.
  3. Remove gender element
  4. Add new element salary with default value 1000 for each employee

JDOM Example – Edit XML File

Here is the java program for above changes.


package com.journaldev.xml.jdom;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;


public class JDOMXMLEditor {

    public static void main(String[] args) throws JDOMException, IOException {
        final Namespace ns = Namespace.getNamespace("https://www.journaldev.com/employees");

        //Get the JDOM document
        org.jdom2.Document doc = useSAXParser("employees.xml");

        //Get list of Employee element
        Element rootElement = doc.getRootElement();
        List<Element> listEmpElement = rootElement.getChildren("Employee", ns);

        //loop through to edit every Employee element
        for (Element empElement : listEmpElement) {

            //change the name to BLOCK letters
            String name = empElement.getChildText("name", ns);
            if (name != null)
                empElement.getChild("name", ns).setText(name.toUpperCase());

            //edit the ID attribute based on Gender
            String gender = empElement.getChildText("gender", ns);
            if (gender != null && gender.equalsIgnoreCase("female")) {
                String id = empElement.getAttributeValue("id");
                empElement.getAttribute("id").setValue(id + "F");
            } else {
                String id = empElement.getAttributeValue("id");
                empElement.getAttribute("id").setValue(id + "M");
            }

            //remove gender element as it's not needed anymore
            empElement.removeChild("gender", ns);

            //add salary element with default value to every employee
            empElement.addContent(new Element("salary", ns).setText("1000"));
        }

        //document is processed and edited successfully, lets save it in new file
        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
        //output xml to console for debugging
        //xmlOutputter.output(doc, System.out);
        xmlOutputter.output(doc, new FileOutputStream("employees_new.xml"));
    }


    //Get JDOM document from SAX Parser
    private static org.jdom2.Document useSAXParser(String fileName) throws JDOMException,
            IOException {
        SAXBuilder saxBuilder = new SAXBuilder();
        return saxBuilder.build(new File(fileName));
    }

}

Notice the use of namespace for retrieving all the elements. Above program produces following output xml.

employees_new.xml


<?xml version="1.0" encoding="UTF-8"?>
<Employees xmlns="https://www.journaldev.com/employees">
  <Employee id="1M">
    <age>25</age>
    <name>PANKAJ</name>
    <role>Java Developer</role>
    <salary>1000</salary>
  </Employee>
  <Employee id="2F">
    <age>34</age>
    <name>MONA</name>
    <role>Manager</role>
    <salary>1000</salary>
  </Employee>
  <Employee id="3M">
    <age>45</age>
    <name>DAVE</name>
    <role>Support</role>
    <salary>1000</salary>
  </Employee>
</Employees>

That’s all for JDOM example to edit XML file in java.

Comments

  1. Zanka33 says:

    definately i have difficulties to post the code 🙁 . In fact i would like to ignore the xmlns,xmlns:xsi, xsi:schemaLocation attributes in root element. Thank you

  2. Zanka33 says:

    Sorry my file looks like

    ......
    .......

  3. Zanka33 says:

    Hi guy !
    thank you for this tutorial, i found it helpfull for me. But i have a kind of troubleshoot, can you help me please ? 😉

    well i’m using your useSAXParser to generate a JDOM document for logic.
    my xml file look like

    …..

    the program works properly when i use the root element dataRecord without namespace like

    …..

    but when using the original final with a rootelement encapsulating namespace and other attribute like stated. The program doesn’t work at all. It is like the JDOM document generated is a null value.

    I tried to find a way to ignore the namespace but i didn’t find a solution yet.

    Please help 😀

    Thank you !

  4. Houssem ZAIER says:

    Thank you for this tutorial. You’ve helped me a lot !

  5. Gaius says:

    Please i have a challenge with editing xml document, can u please send me ur email so we can communicate

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages