This example demonstrate how to convert JDOM Document
object to a String
using the XMLOutputter.outputString(Document doc)
method.
package org.kodejava.jdom;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class JDOMDocumentToString {
public static void main(String[] args) {
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("Mallory"));
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);
// Create an XMLOutputter object with pretty formatter. Calling
// the outputString(Document doc) method convert the document
// into string data.
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
String xmlString = outputter.outputString(document);
System.out.println(xmlString);
}
}
The result of our code snippet:
<?xml version="1.0" encoding="UTF-8"?>
<rows>
<row>
<firstname>Alice</firstname>
<lastname>Mallory</lastname>
<address>Sunset Road</address>
</row>
</rows>
Maven Dependencies
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.6.1</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024