Java XML – JDOM2 – DOMBuilder

Buliding JDOM2 documents from w3c DOM

JDOM2 provides a DOMBuilder that can be used to build a JDOM2 Document from a org.w3c.dom.Document. If there are namespace declarations in the xml document then make sure that while parsing the XML document the setNamespaceAware method of the DocumentBuilderFactory is set to true. Before we look at an example note that it is recommended to use a SAXBuilder to build a JDOM2 Document instead of a DOMBuilder since there is no reason to have both the DOM and JDOM2 Document in memory. Lets look at an example now.

package com.studytrails.xml.jdom;

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

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.DOMBuilder;
import org.xml.sax.SAXException;

public class CreateJdomFromDom {

	private static String xmlSource = "http://feeds.bbci.co.uk/news/technology/rss.xml?edition=int";

	public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
		// create the w3c DOM document from which JDOM is to be created
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// we are interested in making it namespace aware.
		factory.setNamespaceAware(true);
		DocumentBuilder dombuilder = factory.newDocumentBuilder();

		org.w3c.dom.Document w3cDocument = dombuilder.parse(xmlSource);

		// w3cDocument is the w3c DOM object. we now build the JDOM2 object

		// the DOMBuilder uses the DefaultJDOMFactory to create the JDOM2
		// objects.
		DOMBuilder jdomBuilder = new DOMBuilder();

		// jdomDocument is the JDOM2 Object
		Document jdomDocument = jdomBuilder.build(w3cDocument);

		// The root element is the root of the document. we print its name
		System.out.println(jdomDocument.getRootElement().getName()); // prints
																		// "rss"
		
	}
}

Leave a Comment