Easiest way to read an XML file using Selenium Webdriver

DocumentBuilderFactory Class


What is DocumentBuilderFactory Class ?

The javax.xml.Parsers.DocumentBuilderFactory Class API enables applications to obtain a parser that produces DOM object trees from XML documents.

How DocumentBuilderFactory is DECLARED ?

public abstract class DocumentBuilderFactory
   extends Object


What are the most useful METHODS of DocumentBuilderFactory Class ?

  • newDocumentBuilder
  • newInstance
1abstract DocumentBuilder newDocumentBuilder()
This method creates a new instance of a DocumentBuilder using the currently configured parameters.
2static DocumentBuilderFactory newInstance()
This method obtains a new instance of a DocumentBuilderFactory



DocumentBuilder class


What is DocumentBuilder Class ?

The javax.xml.Parsers.DocumentBuilder class API obtains DOM Document instances from an XML document. 
We can obtain a Document from XML using this class.

What are the most useful METHODS of DocumentBuilder Class ?

  • parse(InputSource is) 
The Javax.xml.parsers.DocumentBuilder.parse(InputSource is) method parses the content of the given input source as an XML document and return a new DOM Document object. An IllegalArgumentException is thrown if the File is null.


How to DECLARE DocumentBuilder.parse() ?

public abstract Document parse(InputSource xmlFile)

What PARAMETER it takes ?

xmlFile is the one that you need to pass as parameter here, to parse and create  a document out of it .

What value it RETURNS ?

This method returns a new DOM Document object



How to read an XML file using DocumentBuilderFactory & DocumentBuilder Classes ?






package com.SoftwareTestingAnEasyWay;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class DocumentBuilderFactoryMyDemo{

 public static void main(String[] args) {

  // create a new DocumentBuilderFactory
  DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();

  // configure the DocumentBuilder to be namespace aware
  dbfactory.setNamespaceAware(true);

  try {
   File XmlFile = new File("C:/SoftwareTesting/EasyWay.xml");
   DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
   DocumentBuilder Builder = Factory.newDocumentBuilder();
   Document doc = Builder.parse(XmlFile);                                                                                  
  } catch (ParserConfigurationException ex) {
   ex.printStackTrace();
  } 
}


Recap :

DocumentBuilderFactory a parser that produces DOM object trees from XML documents.
Methods : 
  • newDocumentBuilder
  • newInstance
The javax.xml.Parsers.DocumentBuilder obtains DOM Document instances from an XML document. 
  • parse(InputSource xmlFile)
An XML file can be read using DocumentBuilderFactory & DocumentBuilder Classes .