How to read XML file data in Java || How to create object repository in selenium

As most of the commercial automation tools has feature of object repository concept, which separate application objects from automation scripts, it help us to modify object when AUT object change without going into code.  Also if we create object repository then it reuse throughout scripts from one place.

In Webdriver we can put locator (object) of web elements in to xml, properties, excel file etc at one place, and can separate from test scripts with logically divided into files.

In this post I am going to show you how to read data and put locators into xml files.

We create xml files for object locator like “Header.xml” where put all locators related to header menus, “Login.xml” for locators of login page, “Dashborad.xml” for locator of dashboard page.
Example of “Header.xml” file.

        
      <![CDATA[HOME_MENU_BUTTON]]>  
      <![CDATA[SALES_MENU_BUTTON]]> 
      
          <![CDATA[PANEL_LOGOUT_BUTTON]]> 
      
     



In above xml files I have put three objects locator s, Now below is the java code to read Header.xml file data.
package com.test;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class ReadXMLData {

    private Document doc;
    private String fileName;

    public ReadXMLData(String fileName) {
              this.fileName = fileName;
    }

    public String getData(String locator) {
              SAXReader reader = new SAXReader();
               try {
                      doc = reader.read(fileName);
              } catch (DocumentException e) {
                      // e.printStackTrace();
             }
            String data = doc.selectSingleNode("//" + locator.replace('.', '/')).getText();                                 return data;
    }

    public static void main(String[] str) {
            ReadXMLData readXml = new ReadXMLData("Header.xml");
            String locator1 = readXml.getData("Menu.Home");
            System.out.println(“Home : “locator1);
            String locator2 = readXml.getData("Menu.Sales");
            System.out.println(“Sales  : “locator2);
            String locator3 = readXml.getData("Menu.UserStiing.LogOut");
            System.out.println(“LogOut  : “locator3);

    }

Note: you need to add “jaxen-*.*.*.jar” and “dom4j-*.*.*.jar” jar files for above code.

Run above code you will see data into console:

Home : HOME_MENU_BUTTON
Sales : SALES_MENU_BUTTON
LogOut : PANEL_LOGOUT_BUTTON

2 comments:

  1. How to identify objects from an XML using webdriver?

    ReplyDelete
  2. Hi,
    I got the below error.. could you please help me
    Exception in thread "main" java.lang.NullPointerException
    at com.ding.ReadXMLData.getData(ReadXMLData.java:22)
    at com.ding.ReadXMLData.main(ReadXMLData.java:27)

    ReplyDelete

Leave your comments, queries, suggestion I will try to provide solution