automate xml

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. Therefore, it is used to create our own customized tag and to store data. Because of its systematic data structure feature, it’s preferred by the developer as well as Automation Engineers. With this purpose in mind, to read automate xml, XML data XML Parser is used by Developer. Generally, in most of the application sources, XML is processed by Application and converted into target XML so some data formatted or structure gets changed. Previously QAs used to validate these XML changes manually which is a lot of time-consuming and is also repetitive work that can be automated using selenium & Java.

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

Given these points, this article will help you to understand XML parsing and compare or validate with the expected result. 

Pre-requisite:

  1. IDE – Set up Eclipse or Intellij on the machine
  2. Set up Java on the machine
  3. Configure Maven on the machine
  4. Configure Testng 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 config.properties.
config.properties 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.io.File;
import java.io.FileInputStream;
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");
                props.load(fis);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        public HashMap<String, String> getPropertyAsHashMap() {
            loadProperty();
            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. It is important to realize that this parser is good for 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;
        try{
            dBuilder = dFactory.newDocumentBuilder();
  1. Parse the xml and store data into Document object and normalize.
Document doc = dBuilder.parse(file);
doc.getDocumentElement().normalize();
  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;
import java.io.File;
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;
        try{
            dBuilder = dFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(file);
            doc.getDocumentElement().normalize();
            XPath xpath = XPathFactory.newInstance().newXPath();
            String xpath1 ="company/staff[2]/nickname";
            String result=xpath.compile(xpath1).evaluate(doc);
            return result;
        }catch(Exception e1) {
            e1.printStackTrace();
            return null;
        }
    }
}
  • Step 6: Write Test class using TestNG to assert expected vs actual result: TestNg is the strong automation framework to compare expected result and actual result. And in either case on the basis of past fail it generates an emailable report 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.
XMLParser.getXPathValue(xpathasMap.get("firstEmployeeName")
  1. Assert using TestNg methods: 

 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();
    @Test
    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);
    }
@Test
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: To summarize, after successful completion of the test, an amazing emailable report will be generated.

XML Parser TestNg report

With this in mind, to this end, to download source code of above project refer below link:

To sum up, hope this article helps you to validate XML using Java and TestNG. Let us know if you face any issues or want to rephrase it on query@thoughtcoders.com.

Write A Comment