How do I set XML element’s text content in JDOM?

This example show you how so set text content of XML element. In JDOM we can easily insert text such as HTML tags without worrying about escaping the tags. JDOM will automatically do this conversion.

package org.kodejava.example.jdom;

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.StringReader;

public class JDOMSetTextContent {
    public static void main(String[] args) {
        String xml = "<root>" +
                "    <description>" +
                "    </description>" +
                "</root>";

        SAXBuilder builder = new SAXBuilder();
        try {
            Document document = builder.build(new StringReader(xml));

            Element root = document.getRootElement();
            Element description = root.getChild("description");

            // Adding a text content to the description element. The string
            // will automatically escaped so we don't have to use the 
            // < and > symbol.
            description.setText("This is an <strong>IMPORTANT</strong> " +
                    "description");

            XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
            outputter.output(document, System.out);
        } catch (JDOMException | IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<!-- https://mvnrepository.com/artifact/org.jdom/jdom2 -->
<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6</version>
</dependency>

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply