How do I get mixed content of an xml element?

The following examples demonstrate how to read mixed content of an xml element. A mixed content can have more than one type of content such as text (Text), comment (Comment), CDATA (CDATA) or some child elements (Element).

You also see that we can remove the mixed content from the element by calling the remove method of the List just like what we do with a collection of data.

package org.kodejava.example.jdom;

import org.jdom.*;
import org.jdom.input.SAXBuilder;

import java.io.IOException;
import java.io.StringReader;
import java.util.List;

public class JDOMMixedContent {
    public static void main(String[] args) {
        String xml = "<root>" +
                "    <data>" +
                "        <!-- This element contains application data -->" +
                "        User Information" +
                "        <![CDATA[<table><tr><td>-data-</td></tr></table>]]>" +
                "        <field name=\"username\">alice</field>" +
                "    </data>" +
                "</root>";

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

            // Reading the mixed content of an xml element and iterate
            // the result list. This list object can contains any of the
            // following objects: Comment, Element, CDATA, DocType,
            // ProcessingInstruction, EntityRef and Text.
            List content = data.getContent();

            for (Object o : content) {
                if (o instanceof Comment) {
                    Comment comment = (Comment) o;
                    System.out.println("Comment   = " + comment);
                } else if (o instanceof Element) {
                    Element element = (Element) o;
                    System.out.println("Element   = " + element);
                } else if (o instanceof CDATA) {
                    CDATA cdata = (CDATA) o;
                    System.out.println("CDATA     = " + cdata);
                } else if (o instanceof DocType) {
                    DocType docType = (DocType) o;
                    System.out.println("DocType   = " + docType);
                } else if (o instanceof ProcessingInstruction) {
                    ProcessingInstruction pi = (ProcessingInstruction) o;
                    System.out.println("PI        = " + pi);
                } else if (o instanceof EntityRef) {
                    EntityRef entityRef = (EntityRef) o;
                    System.out.println("EntityRef = " + entityRef);
                } else if (o instanceof Text) {
                    Text text = (Text) o;
                    System.out.println("Text      = " + text);
                }
            }

            // Remove the second mixed content which is the CDATA content.
            content.remove(2);
        } catch (JDOMException | IOException e) {
            e.printStackTrace();
        }
    }
}

Here are the result of our program:

Text      = [Text:         ]
Comment   = [Comment: <!-- This element contains application data -->]
Text      = [Text:         User Information        ]
CDATA     = [CDATA: <table><tr><td>-data-</td></tr></table>]
Text      = [Text:         ]
Element   = [Element: <field/>]
Text      = [Text:     ]

How do I build xml CDATA sections?

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.example.jdom;

import org.jdom.CDATA;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.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();
        }
    }
}

How do I set XML element’s text content?

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.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.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 
            // &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 | IOException e) {
            e.printStackTrace();
        }
    }
}

How do I get xml element’s text content?

package org.kodejava.example.jdom;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

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

public class JDOMElementTextContent {
    public static void main(String[] args) {
        String xml = "<root>" +
                "    <paragraph>" +
                "        Lorem ipsum dolor sit amet, consectetur adipisicing " +
                "        elit, sed do eiusmod tempor incididunt ut labore et " +
                "        dolore magna aliqua. Ut enim ad minim veniam, quis " +
                "        nostrud exercitation ullamco laboris nisi ut aliquip " +
                "        ex ea commodo consequat. Duis aute irure dolor in " +
                "        reprehenderit in voluptate velit esse cillum dolore " +
                "        eu fugiat nulla pariatur. Excepteur sint occaecat " +
                "        cupidatat non proident, sunt in culpa qui officia " +
                "        deserunt mollit anim id est laborum." +
                "    </paragraph>" +
                "</root>";

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

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

            // Returns the textual content directly held under this element as 
            // a string. This includes all text within this single element, 
            // including whitespace and CDATA sections if they exist.
            String content = paragraph.getText();
            System.out.println("content = " + content);

            // Returns the textual content of this element with all surrounding
            // whitespace removed. If no textual value exists for the element,
            // or if only whitespace exists, the empty string is returned.
            String contentTrimmed = paragraph.getTextTrim();
            System.out.println("contentTrimmed = " + contentTrimmed);

            // Returns the textual content of this element with all surrounding
            // whitespace removed and internal whitespace normalized to a single
            // space.If no textual value exists for the element, or if only
            // whitespace exists, the empty string is returned.
            String contentNormalize = paragraph.getTextNormalize();
            System.out.println("contentNormalize = " + contentNormalize);
        } catch (JDOMException | IOException e) {
            e.printStackTrace();
        }
    }
}

How do I get xml attribute as an integer value?

In this example you can see how we can read xml attribute value as an integer value instead of string. JDOM provides method such as getIntValue(), getLongValue(), getFloatValue(), getDoubleValue() to get numerical values. For boolean value we can use the getBooleanValue() method.

package org.kodejava.example.jdom;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

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

public class JDOMIntegerAttributeValue {
    public static void main(String[] args) {
        String xml = "<root><table width=\"100\"/></root>";

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

            Element child = document.getRootElement().getChild("table");
            int tableWidth = child.getAttribute("width").getIntValue();
            System.out.println("tableWidth = " + tableWidth);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I add and remove elements from xml document?

The List returned by the getChildren() method call is a java.util.List. Any modification to the List object immediately reflected in the backing document. This make the manipulation of the XML document easy.

You can also see how we can add a new Element to the document by calling the addContent() method.

package org.kodejava.example.jdom;

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

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;

public class JDOMAddRemoveElement {
    public static void main(String[] args) {
        String xml = "<root>" +
                "   <user name=\"Alice\" age=\"21\" dob=\"20-01-1988\"/>" +
                "   <user name=\"Bob\" age=\"23\" dob=\"01-05-1986\"/>" +
                "</root>";

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

            // Adding a new element to the root of the document using the
            // addContent method.
            document.getRootElement().addContent(
                    new Element("people").setAttribute("id", "1"));
            document.getRootElement().addContent(
                    new Element("people").setAttribute("id", "1"));

            // Add a new element. By adding a new element to the List of
            // children we can modified the xml document. Using 
            // java.util.List makes the modification of XML document 
            // simple and easy.
            List<Element> children = document.getRootElement().getChildren();
            children.add(new Element("user")
                    .setAttribute("name", "Carol")
                    .setAttribute("age", "25")
                    .setAttribute("dob", "06-03-1984"));

            // Add element to the beginning of the xml document.
            children.add(0, new Element("user")
                    .setAttribute("name", "Jimmy")
                    .setAttribute("age", "25")
                    .setAttribute("dob", "16-05-1984"));

            // Remove the fourth element.
            children.remove(3);

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

The result of this code is:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <user name="Jimmy" age="25" dob="16-05-1984" />
  <user name="Alice" age="21" dob="20-01-1988" />
  <user name="Bob" age="23" dob="01-05-1986" />
  <people id="1" />
  <user name="Carol" age="25" dob="06-03-1984" />
</root>

How do I navigating the XML elements tree?

package org.kodejava.example.jdom;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.List;

public class JDOMTraversingElement {
    public static void main(String[] args) {
        String xml = "<root>" +
                "    <country name=\"Japan\" capital=\"Tokyo\"/>" +
                "    <country name=\"France\" capital=\"Paris\"/>" +
                "    <country name=\"Italy\" capital=\"Rome\"/>" +
                "    <country name=\"England\" capital=\"London\"/>" +
                "    <country name=\"Indonesia\" capital=\"Jakarta\"/>" +
                "    <city name=\"Denpasar\"/>" +
                "    <city name=\"Bangkok\"/>" +
                "    <city name=\"Mumbai\"/>" +
                "    <city name=\"Delhi\"/>" +
                "</root>";

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

            // Getting the root element
            Element root = document.getRootElement();

            // Getting the first child
            Element country = root.getChild("country");
            System.out.println("Name: " + country.getAttribute("name")
                    .getValue());
            System.out.println("Capital: " + country.getAttribute("capital")
                    .getValue());
            System.out.println("----------------------------------------");

            // Getting all children of the root
            List<Element> elements = root.getChildren();
            for (Element element : elements) {
                if (element.getName().equals("country")) {
                    System.out.println(MessageFormat.format("{0} -> {1}",
                            element.getAttribute("name").getValue(),
                            element.getAttribute("capital").getValue()));
                } else if (element.getName().equals("city")) {
                    System.out.println(element.getAttribute("name")
                            .getValue());
                }
            }
            System.out.println("----------------------------------------");

            // Getting all children of the root named city
            List<Element> cities = root.getChildren("city");
            for (Element city : cities) {
                System.out.println(city.getAttribute("name").getValue());
            }
        } catch (JDOMException | IOException e) {
            e.printStackTrace();
        }
    }
}

How do I add attributes to an XML elements?

The program below will show you how to add attributes to an xml elements. Using JDOM library this can be easily done by calling the Element‘s setAttribute(String name, String value) method.

package org.kodejava.example.jdom;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
import org.jdom.output.Format;

import java.io.IOException;

public class JDOMAddAttribute {
    public static void main(String[] args) {
        Document doc = new Document();
        Element root = new Element("root");
        
        //
        // Create 
        //
        Element child = new Element("row").setAttribute("userid", "alice");
        
        //
        // Create 
        //
        Element name = new Element("name")
                .setAttribute("firstname", "Alice")
                .setAttribute("lastname", "Starbuzz");

        child.addContent(name);
        root.addContent(child);
        doc.addContent(root);

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

And here goes the output:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <row userid="alice">
    <name firstname="Alice" lastname="Starbuzz" />
  </row>
</root>

How do I create an XML document using JDOM?

In this small program you can see how to use JDOM to create a simple xml file. Below you’ll see how to create elements of the xml document, set some text for the element.

After that you can see how to use the XMLOutputter class to write the JDOM document into file and display it on the screen. To make the output better we can apply a Format to our xml document.

package org.kodejava.example.jdom;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
import org.jdom.output.Format;

import java.io.FileWriter;
import java.io.IOException;

public class JDomCreatingXml {
    public static void main(String[] args) {
        //
        // 
        //     
        //         Alice
        //         Starbuzz
        //         
Sunset Read
//
// // Document document = new Document(); Element root = new Element("rows"); // // Creating a child for the root element. Here we can see how to // set the text of an xml element. // Element child = new Element("row"); child.addContent(new Element("firstname").setText("Alice")); child.addContent(new Element("lastname").setText("Starbuzz")); child.addContent(new Element("address").setText("Sunset Road")); // // Add the child to the root element and add the root element as // the document content. // root.addContent(child); document.setContent(root); try { FileWriter writer = new FileWriter("userinfo.xml"); XMLOutputter outputter = new XMLOutputter(); // // Set the XLMOutputter to pretty formatter. This formatter // use the TextMode.TRIM, which mean it will remove the // trailing white-spaces of both side (left and right) // outputter.setFormat(Format.getPrettyFormat()); // // Write the document to a file and also display it on the // screen through System.out. // outputter.output(document, writer); outputter.output(document, System.out); } catch (IOException e) { e.printStackTrace(); } } }

This program will output the following XML document:

<?xml version="1.0" encoding="UTF-8"?>
<rows>
  <row>
    <firstname>Alice</firstname>
    <lastname>Starbuzz</lastname>
    <address>Sunset Road</address>
  </row>
</rows>

How do I create a Document object?

The following example show you how to create a simple Document object in JDOM. We can create a new document directly by creating a new instance of the Document class, for additional information we can pass an Element as an argument.

To create a Document from an existing XML file we can use the SAXBuilder. Beside reading from file we can also build a Document from stream and URL.

package org.kodejava.example.jdom;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import java.io.File;
import java.io.IOException;

public class JDOMCreateDocument {
    public static void main(String[] args) {
        //
        // Creating a document with an Element as the parameter.
        //
        Element element = new Element("root");
        element.setText("Hello World");
        
        Document document = new Document(element);
        System.out.println("root.getName() = " +
                document.getRootElement().getName());

        //
        // We can also create a document from a file, stream or URL using
        // a SAXBuilder
        //
        SAXBuilder builder = new SAXBuilder();
        try {
            //
            // Build a document from a file using a SAXBuilder.
            // The content of data.xml file:
            //
            // 
            //     
            //         alice
            //         secret
            //     
            // 
            //
            document = builder.build(new File("data.xml"));
            Element root = document.getRootElement();
            System.out.println("root.getName() = " + root.getName());
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}