How do I build XML CDATA sections in JDOM?

This example demonstrates how to add CDATA section into an xml document. A CDATA section indicates a block that shouldn’t be parsed. To build a CDATA section just wrap the string with a CDATA object.

package org.kodejava.jdom;

import org.jdom2.CDATA;
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;


public class JDOMBuildCDATASection {
    public static void main(String[] args) {
        String xml = """

        SAXBuilder builder = new SAXBuilder();
        try {
            Document document = StringReader(xml));
            Element root = document.getRootElement();
            Element comments = root.getChild("comments");

            Element comment = comments.getChild("comment");

            // Using the setContent and addContent to add CDATA section
            // into  the xml element.
                    new CDATA("<b>This is a bold string</b>."));
                    new CDATA("<i>And this an italic string</i>."));

            XMLOutputter outputter =
                    new XMLOutputter(Format.getPrettyFormat());
            outputter.output(document, System.out);

            // Reading a CDATA section is simply done by calling the 
            // getText method. It doesn't care if it was a simple string
            // or a CDATA section, it will just return the content as 
            // string.
            String text = comment.getText();
            System.out.println("Text = " + text);
        } catch (JDOMException | IOException e) {

The output of the code snippet above:

<?xml version="1.0" encoding="UTF-8"?>
    <comment><![CDATA[<b>This is a bold string</b>.]]><![CDATA[<i>And this an italic string</i>.]]></comment>
Text = <b>This is a bold string</b>.<i>And this an italic string</i>.

Maven Dependencies


Maven Central


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.