Java examples on org.jdom
- How do I read an XML document using JDOM?
- How do I build xml CDATA sections?
- How do I add and remove elements from xml document?
- How do I create an XML document using JDOM?
- How do I convert JDOM Document to String?
- How do I get xml attribute as an integer value?
- How do I remove an element from XML document?
- How do I get xml element's text content?
- How do I set XML element's text content?
- How do I remove an attribute from XML element?
- How do I navigating the XML elements tree?
- How do I add attributes to an XML elements?
- How do I create a Document object?
- How do I get mixed content of an xml element?
How do I convert JDOM Document to String?
This example demonstrate how to convert JDOM Document object to a String using the XMLOutputter.outputString(Document doc) method.
package org.kodejava.example.jdom;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.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);
}
}