Automate XML Parser using Java & Selenium

How to Parse XML Data and Test XML using Java & Selenium?

What is XML? XML or Extensible Markup Language is not a programming language like HTML is. It is used to create our own customized tag and to store data. Due to its systematic data structure feature, it’s preferred by the developer as well as Automation Engineers. To read XML data XML Parser is used by Developer. In most of the application sources, XML is processed by Application and converted into target XML so some data formatted or structure getting changed. Previously QAs used to validate these XML changes manually which is a lot of time-consuming and is also a repetitive work that can be automated using selenium & Java.

This automation testing approach for XML parse & validation can be used in operations like feed file, data file, CSV file, or in the database testing. Most of the banking applications, payment gateways, etc companies have this type of testing requirement.

This article will help you to understand XML parsing and compare or validate with the expected result. 


  1. IDE – Eclipse or Intellij should be set up on the machine
  2. Java  should be set up on the machine
  3. Maven should be configured on the machine
  4. TestNg should be configured on the machine

Steps to automate XML Parser and validation using Java & Selenium:

  • Step 1: Create Java Project and add TestNG, Maven dependency in POM.xml file
TestNG dependency in pom.xml

XML Parser automation test framework Folder Structure:

XML Parser testing framework folder structure
  • Step 2: Analyze XML and find XPath of required nodes:
Find XPath from XML nodes/tags

Find/Generate XPath from XML Node in XML File:

Illustration to find XPath of XML nodes (Refer to above XML screenshot or image)

  1. firstEmployeeName -> company/staff[1]/firstname   -> Manish
  2. SecondEmployeeName -> company/staff[2]/firstname -> Ravish
  3. firstEmployeeNickName -> company/staff[1]/nickname -> Monu
  4. secondEmployeeNickName -> company/staff[2]/nickname -> Ravi
XPath of xml nodes
  • Step 3: Create a resource folder in Project and keep properties file in file
  • Step 4: Write Property Reader which return all properties in HashMap.

Also, Refer our article on – Store Excel Data With HashMap in Selenium

Property Reader code Using HashMap in Java:

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Properties;
public class PropReader {
    public class propertyReader {
        private String propertyName = null;
        private Properties props;
        public propertyReader(String propertyName) {
            this.propertyName = propertyName;
         private void loadProperty() {
            try {
                props = new Properties();
                FileInputStream fis = new FileInputStream(System.getProperty("user.dir") + File.separator + "resources"
                        + File.separator + propertyName + ".properties");
            } catch (Exception e) {
        public HashMap<String, String> getPropertyAsHashMap() {
            HashMap<String, String> map = new HashMap<String, String>();
            for (Entry<Object, Object> entry : props.entrySet()) {
                map.put((String) entry.getKey(), (String) entry.getValue());
            return map;
  • Step 5: Write XML Parser Java Code to get value on the basis of Xpath:

Java provides DOM Parser, SAX parser, Stax Parser, and JAXB Parser. DOM parser is one of the best parsers which is easy to use and supports XPath. This parser is good form small to moderate XML parser as it stores XML in memory so for larger XMLs it degraded the performance.  Refer below for code and detailed implementations:

  1. First load the XML file using file class.
String filePath= System.getProperty("user.dir")+ File.separator+"resources"+File.separator+"staff.xml";
File file = new File(filePath);
  1. Obtain a new instance of DocumentBuilderFactory. This is
  2. basically an abstract class that enables to parse XML File and produces a DOM tree.
  1. Creates a new instance of a DocumentBuilder using the currently configured parameters.
DocumentBuilder dBuilder;
            dBuilder = dFactory.newDocumentBuilder();
  1. Parse the xml and store data into Document object and normalize.
Document doc = dBuilder.parse(file);
  1. Create a new instance of X Path Object
   XPath xpath = XPathFactory.newInstance().newXPath();

vi.  Compile XPath and evaluate to get XPath data from XPath.

String result=xpath.compile(xpath1).evaluate(doc);

Combined code of all steps of Step-5: (XML Parser Java Code)

import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
public class XMLParser {
    public static String getXPathValue(String XPath){
        String filePath= System.getProperty("user.dir")+ File.separator+"resources"+File.separator+"staff.xml";
        File file = new File(filePath);
        DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
            dBuilder = dFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(file);
            XPath xpath = XPathFactory.newInstance().newXPath();
            String xpath1 ="company/staff[2]/nickname";
            String result=xpath.compile(xpath1).evaluate(doc);
            return result;
        }catch(Exception e1) {
            return null;
  • Step 6: Write Test class using TestNG to assert expected vs actual result: TestNg is the strong automation framework which is used to compare expected result and actual result. And on the basis of past fail it generates an emailable report which can be used to share with Management. 
  1. Create object of Property Reader class to load property file.
   propertyReader prop = new propertyReader("config");
  1. Convert get property file data into HashMap
HashMap<String, String> xpathasMap= prop.getPropertyAsHashMap();
  1. Get X Path Value from XML using XML Parser class.
  1. Assert using TestNg methods: 

Assertions are done with actual with the expected results. The expected result could be taken from database/CSV or excel or API response. So using TestNG we can compare actual results with the expected results.

Assert.assertEquals(actualFirstEmployeeName, expectedFirstEmployeeName);

Combined code of all steps of Step-6: (Test XML Java Code)

import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.HashMap;
public class TestXML {
   propertyReader prop = new propertyReader("config");
   HashMap<String, String> xpathasMap= prop.getPropertyAsHashMap();
    public void TestEmployeeName(){
        String expectedFirstEmployeeName="Manish";
        String actualFirstEmployeeName=    XMLParser.getXPathValue(xpathasMap.get("firstEmployeeName"));
        Assert.assertEquals(actualFirstEmployeeName, expectedFirstEmployeeName);
        String expectedsecindEmployeeName="Ravish";
        String actualsecondEmployeeName= XMLParser.getXPathValue(xpathasMap.get("SecondEmployeeName"));
        Assert.assertEquals(actualsecondEmployeeName, expectedsecindEmployeeName);
public void testNickName(){
    String expectedFirstEmployeeNickName="Monu";
    String actualFirstEmployeeNickName= XMLParser.getXPathValue(xpathasMap.get("firstEmployeeNickName"));
    Assert.assertEquals(actualFirstEmployeeNickName, expectedFirstEmployeeNickName);

Step 7: Go to TestNg output directory and open emailable report: After successful completion of the test, an amazing emailable report will be generated.

XML Parser TestNg report

To download source code of above project refer below link:

Hope this article helps you to validate XML using Java and TestNG. Let us know if you face any issue on

Subscribe to our Newsletter:

5 3 votes
Article Rating

Subscribe to our Newsletter:

Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x
Open chat
Feel free to contact