Sunday, May 7, 2017

WebDriver - Reading XML Files

WebDriver - Reading XML Files


There can be many ways of reading an XML file using WebDriver & C# like XmlDocument, XmlReader, XDocument etc. In this post we will look into very simple examples of reading XML files using XDocument or XElement.

Below is the XML file ("a.XML") which we will be using in first 3 examples.


Example 1 - Reading an XML File using WebDriver & C#

Firstly we are creating a new XDocument from file "a.XML". Load method uses an underlying XmlReader to read the XML into an XML tree. Elements() method returns a collection of the child elements. Then using foreach loop we are printing the XML document.


List of references with this project. Make sure to use System.Xml & System.Xml.Linq.


Results of running the above example


Example 2 - Reading an XML File using WebDriver & C#

This example is similar to the first one except that we are using XElement instead of XDocument.

XDocument in a way represents a whole XML document. It is normally composed of a number of elements whereas XElement represents an XML element (with attributes, children etc). It is part of a larger document. [Via]


List of references with this project


Results of running the above code


Example 3 - Reading an XML File using WebDriver & C#

In this example we are retrieving the entry names (Entry 01, Entry 02) and printing them on the console. Moreover, if we find "Entry 01", we are searching this in the google.com also. This is just one of those very simple examples where we retrieve the value from the XML file and use them in some application.


Apart from navigating to google.com and searching for "Entry 01", it also shows the below result:


Below is the XML file ("b.XML") which we will be using in this fourth example.


Example 4 - Reading an XML File using WebDriver & C#

In this example we are retrieving usernames and passwords. These usernames and passwords are further being used to login in the gmail. This is also very simple example of how you can retrieve the required values from XML and use them in some application.


Apart from navigating to gmail.com and trying to login, it also shows the below result: