Reading all XML tags with values in XML file using Selenium

package com.test;

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

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;

public class XMLRead {

  public static void main(String argv[]) throws ParserConfigurationException, SAXException, IOException {

      File fXmlFile = new File(Absolute Path of XML file); 
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        
        doc.getDocumentElement().normalize();
        System.out.println("Root element " + doc.getDocumentElement().getNodeName());
        NodeList nodeList=doc.getElementsByTagName("*");       
         for (int count = 0; count < nodeList.getLength(); count++) 
             {
                Node tempNode = nodeList.item(count);
                // make sure it's element node.
                if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
                    // get node name and value
                    System.out.println("\nNode Name  =" + tempNode.getNodeName()); // + " [OPEN]");
                    System.out.println("Node Value  =" + tempNode.getTextContent());
                    System.out.println("Node Name =" + tempNode.getNodeName()); // + " [CLOSE]");
                    }
              }
            }
          }



Sample XML File :

<?xml version="1.0" encoding="UTF-8"?>
<addresses xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation='test.xsd'>
  <address>
    <name>Joe Tester</name>
    <street>Baker street 5</street>
  </address>
</addresses>


Output:

Node Name =address

Node Name  =name
Node Value  =Joe Tester
Node Name =name

Node Name  =street
Node Value  =Baker street 5
Node Name =street



Leave a comment