java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to set XML element's text content?

This example show you how so set text content of an 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 com.javacoderanch.example.jdom;

import org.jdom.input.SAXBuilder;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
import org.jdom.output.Format;


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

        SAXBuilder builder = new SAXBuilder();
        try {
            Document document = 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 &lt; and
            // &gt; symbol.
            description.setText("This is an <strong>IMPORTANT</strong> " +

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