Site icon TestingDocs.com

How to Parse an XML file with JDOM?

Overview

Let us write a sample JDOM exercise Java program the reads the XML file and lists all the environment names in the XML file. Included are the sample  XML file and the Java program.

In order to use JDOM library in our program, we need to place the below maven dependency in your project pom file.

JDOM Maven dependency

<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.5</version>
</dependency>

 

Sample XML File

Let us consider the below sample xml file that has details about testing environments. The file name is “sample.xml”

<?xml version="1.0" encoding="UTF-8"?>
<environments>
   <environment>
   <name>QA</name>
   <username>qa</username>
   <password>qa1234</password>
      <browsercontext>
         <Browser>Firefox</Browser>
         <OS>Linux</OS>
      </browsercontext>
</environment>
<environment>
    <name>STAGING</name>
    <username>stage</username>
    <password>stage1234</password>
        <browsercontext>
           <Browser>Chrome</Browser>
           <OS>Windows</OS>
        </browsercontext>
</environment>
<environment>
      <name>PRODUCTION</name>
      <username>prod</username>
      <password>prod1234</password>
         <browsercontext>
            <Browser>Chrome</Browser>
            <OS>Windows</OS>
         </browsercontext>
</environment>
</environments>

 

Sample Java Program

public class JDOMExercise {

public static void main(String[] args) throws IOException, JDOMException {
String filename = "sample.xml";
PrintStream out = System.out;

SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File(filename));
Element root = doc.getRootElement();

List<Element> environments = root.getChildren("environment");
out.println("The xml file has "+ environments.size() + " environments");
Iterator<Element> i = environments.iterator();
while (i.hasNext()) {
Element environment = (Element) i.next();
out.println( "Environment:" + environment.getChildText("name"));

}

}
}

 

Program Output

The xml file has 3 environments
Environment:QA
Environment:STAGING
Environment:PRODUCTION

 

 

SAXBuilder builds a JDOM Document using a SAX parser.

Document class represents an XML document. It has methods that allow access to the root element as well as the and other document-level information.

The Element class represents an XML element. It has methods that allow us to get and manipulate its child elements and content. We can directly access the element’s content, manipulate its attributes etc.

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/in/java/

Exit mobile version