How to Read XML File in Java Selenium

This article describes the ways to read XML file in Java and get XML node values by providing XML Node names and by giving XPath for the specific XML node element.While automating an application ( using Selenium or LeaFT or Web Services Automation ) at times we need to read test data from a XML file. On the off chance that you have a similar requirement, this article will facilitate your work.

Read XML FiLE in Java myskillpoint

We will use the following sample XML file to read its values.

Read XML file in java Selenium

Read XML File in Java and Get XML Node Values by Providing Node Name

The following example shows how to read XML file in Java and print all node values.

Output

Root element name is: item
(0) Child Node Name : mobile
Mobile id: 101
Brand Name: Samsung
Model Name: Samsung Galaxy F62
Mobile Price: 320$
(1) Child Node Name : mobile
Mobile id: 102
Brand Name: Motorola
Model Name: Motorola G60
Mobile Price: 800$
(2) Child Node Name : mobile
Mobile id: 103
Brand Name: Apple
Model Name: Apple iPhone12
Mobile Price: 1050$
(3) Child Node Name : mobile
Mobile id: 104
Brand Name: Oneplus
Model Name: Oneplus Nord CE 5G
Mobile Price: 305$

Read XML File in Java and Get XML Node Values by Providing XPath

We will read the value of brand tag for the second mobile item.

Output

Brand Name is: Motorola

Conclusion

We have learned two different ways to read the value from an XML file in Java. You can use either of them as per your requirement. Hope you will find this article helpful. Please don’t forget to share this article with your friends.

Recommended Posts

Leave a Reply