How do I set XML element's text content?

Category: org.jdom, viewed: 1459 time(s).

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 org.kodejava.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;

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

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 &lt; and
            // &gt; symbol.
            //
            description.setText("This is an <strong>IMPORTANT</strong> " +
                    "description");

            XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
            outputter.output(document, System.out);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats