Java XML – JDOM2 – StAXBuilder

In the previous examples we saw how to bulid a JDOM2 document from w3c Document. We also saw how to build a JDOM2 Document using a SAXBuilder. In this example we look at how to create a JDOM2 document using a StAXEventBuilder or a StAXStreamBuilder.

StAXEventBuilder

StAXEventBuilder builds a JDOM2 document using a StAX based XMLEventReader. We first create an XMLInputFactory. We then use the factory to create an XMLEventReader by passing the XML file. The XMLEventReader is then passed to the StAXEventBuilder. Note that StAXEvenBuilder has no control over the validation process and therefore to create a validating builder set the appropriate property on the XMLInputFactory. Here’s an example. The XML file can be downloaded from here

package com.studytrails.xml.jdom;

import java.io.FileNotFoundException;
import java.io.FileReader;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;

import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.StAXEventBuilder;

public class JdomUsingXMLEventReader {

	public static void main(String[] args) throws FileNotFoundException, XMLStreamException, JDOMException {
		XMLInputFactory factory = XMLInputFactory.newFactory();

		XMLEventReader reader = factory.createXMLEventReader(new FileReader("bbc.xml"));

		StAXEventBuilder builder = new StAXEventBuilder();
		Document jdomDoc = builder.build(reader);
		System.out.println(jdomDoc.getRootElement().getName()); // prints "rss"
		System.out.println(jdomDoc.getRootElement().getNamespacesIntroduced().get(1).getURI()); // prints "http://search.yahoo.com/mrss/"

	}
}

StAXStreamBuilder

StAXStreamBuilder builds a JDOM2 document from a StAX based XMLStreamReader. For JDOM2 XMLStreamReader is more efficient then XMLEventReader and should be the first choice. Here’s an example

package com.studytrails.xml.jdom;

import java.io.FileNotFoundException;
import java.io.FileReader;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.StAXStreamBuilder;

public class JdomUsingXMLStreamReader {

	public static void main(String[] args) throws FileNotFoundException, XMLStreamException, JDOMException {
		XMLInputFactory factory = XMLInputFactory.newFactory();
		XMLStreamReader reader = factory.createXMLStreamReader(new FileReader("bbc.xml"));

		StAXStreamBuilder builder = new StAXStreamBuilder();
		Document jdomDoc = builder.build(reader);
		System.out.println(jdomDoc.getRootElement().getName());  // prints "rss"
		System.out.println(jdomDoc.getRootElement().getNamespacesIntroduced().get(1).getURI());// prints "http://search.yahoo.com/mrss/"
	}
}

Leave a Comment