Last Updated:

Read an XML file in Java using JDOM Parser

XML file in Java

JDOM Parser is not part of the standard JDK, so to use JDOM you will need to download the Jar file from the official website and add it to the project. I'm using maven, so I'll just add the following code depending:

JDOM provides four wrapper classes with which we can get a JDOM Document object. The JDOM Document object itself contains many methods for retrieving the root element, a list of child elements, attribute values, and an element value by name.

JDOM provides the following classes:

  1. The class uses the DOM Parser to parse the XML and transform it into the . org.jdom2.input.DOMBuilderJDOM Document
  2. The class uses SAX Parser to parse XML and transform it into .org.jdom2.input.SAXBuilderJDOM Document
  3. The class uses stax Event Parser to parse XML and transform it into .org.jdom2.input.StAXEventBuilderJDOM Document
  4. The class uses STAX Stream Parser to parse XML and transform it into a JDOM
  5. The class contains the most commonly used methods for working with XML: retrieving the root element, reading data, editing and writing the contents of
  6. The class contains other commonly used methods for retrieving a list of child elements, child element values, and attribute

Example of reading an XML file using JDOM Parser

The following is a program for reading an XML file to a list of objects using JDOM Parser.

Contents of the students.xml file:

Below we write a class that will store information about one Student element:

Ниже представлена программа для считывания XML файла с помощью ,  и  в список объектов Student:DOMBuilderSTAXParserSAXParser

Let's run the program and see the output to the console:

As you can see, two more methods of obtaining . In order to test each of them, simply replace the following line of the program as shown below:JDOM Document

Each of these methods returns a valid JDOM Document that we can work with already within the JDOM, so the result of execution will always be the same.

Here is such a simple example of reading an XML file using JDOM Parser and any of the DOM Parser, SAX Parser or STAX Parser.