Java XML – JDOM2 – Outputter

Introduction

In the earlier tutorials we looked at how to create a JDOM2 document from SAX ,DOM and StAX. In this tutorial we learn how to output JDOM2 as XML, DOM, SAX, StAXEvent and StaxStream. Lets look at the important classes

Important Classes

  • XMLOutputter – This is probably the most useful outputter. It outputs the JDOM2 document as a stream of byes that can be written to a file. In other words, to create an XML file from JDOM2 document use this class. The most useful methods is public final void output(Document doc, OutputStream out). The encoding of the writer should match the encoding of the Format object of the Outputter. The conversion can be customized by using a custom XMLOutputProcessor
  • DOMOutputter – Outputs a JDOM2 document as a w3c DOM Document. It can be configured by passing in three types of objects – DOMAdapter, Format and DOMOutputProcessor. A DOMAdapter is an interface whose implementation interfaces with a DOMParser to create DOM objects. The default implementation is JAXPDOMAdapter. The DOMOutputProcessor is the main class responsible for the conversion. The important method is public final void output(Document doc, XMLStreamWriter out) throws XMLStreamException. An Element can also be passed instead of a Document
  • SAXOutputter – Outputs a JDOM2 document as a stream of SAX2 Events. It takes in a ContentHandler to process the SAX events. It can also be configured using an ErrorHandler, DTDHandler, EntityResolver, LexicalHandler and DeclHandler. It also uses a SAXOutputProcessor that does the bulk of the processing. The most useful constructor is public SAXOutputter(ContentHandler contentHandler) and the the output method is public final void output(Document doc, XMLStreamWriter out) throws XMLStreamException
  • StAXEventOutputter Outputs the JDOM2 document as a series of events that can be read by an XMLEventConsumer. The default processor to process the conversion is DefaultStAXEventProcessor. This can be customized, if required. The most useful method is public final void output(Document doc, XMLEventConsumer out) throws XMLStreamExceptionThe format can also be specified. The following formats are available :
    • for pretty printing – Format.getPrettyFormat()
    • for whitespace-normalized output – Format.getCompactFormat()
    • for unmodified-format output – Format.getRawFormat()
  • StAXStreamOutputter – Outputs the JDOM2 document as a stream that is handled by XMLStreamWriter. Here’s how the main method looks public final void output(Element element, XMLStreamWriter out) throws XMLStreamException. The default processor is DefaultStAXStreamProcessor
  • StAXStreamReader – Outputs the JDOM2 document as an XMLStreamReader.

Example

Now lets see the outputters in action

Leave a Reply

Your email address will not be published. Required fields are marked *