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;

import java.io.IOException;
import java.io.StringReader;

public class JDOMBuildCDATASection {
    public static void main(String[] args) {
        String xml = """
                <root>
                   <comments>
                       <comment></comment>
                   </comments>
                </root>""";

        SAXBuilder builder = new SAXBuilder();
        try {
            Document document = builder.build(new 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.
            comment.setContent(
                    new CDATA("<b>This is a bold string</b>."));
            comment.addContent(
                    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) {
            e.printStackTrace();
        }
    }
}

The output of the code snippet above:

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

Maven Dependencies

<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6.1</version>
</dependency>

Maven Central

Wayan

Leave a Reply

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