Java XML – Example JDOM2 Usage

Building JDOM2 Document

In this tutorial we look at an example of how to build and navigate through a JDOM2 document from an XML source (in this case, a BBC News “Technology” RSS feed). We first use the org.jdom2.input.SAXBuilder class to create the JDOM2 document from the source (more details and options on the SAXBuilder class will be covered in later tutorials). Once we obtain the JDOM2 Document there are various JDOM2 methods used to access the elements, which will be covered in the next section of this tutorial.

Accessing JDOM2 Components

JDOM2 is a java representation of an XML document. In other words, each XML component is represent as a java object. JDOM2 has convenient methods to access the various components. Here are some of the key use cases (the number in the bracket corresponds to the line number in the example) :

  • Obtaining the root element (25,28) – Root Element is the topmost Element of the document
  • Obtaining the Namespace added by a node (32)
  • Obtaining the contents of a particular node (43) – The node is traveresed recursively till all content is found
  • Obtaining a child of an Element (50)
  • Obtaining all children of an Element(54)
  • Obtaining the first child of a particular type and name e.g. the first text node with name ‘link’ (62)
  • Obtaining the first child of a particular type and name and from a specified namespace e.g. the first text node with name ‘link’ from namespace ‘atom'(70)
  • Obtaining all children with a specific name (75)
  • Iterating through all the descendants of an Element and obtaining Elements with specific name and from a specific Namespace (85)

This is not an exhaustive list of use cases but it gives an idea of what can be achieved. If you have a specific requirement then do post it as a comment and we would be glad to answer it

Leave a Reply

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