Reading XML file using Katalon

Hi,

I want to read following xml file in katalon,

1). I need to count all report tags.
2). Read each R tags under report tag and its value.

Glad if anyone help on this.

I was able to get the report count using following code, but need to know any better way to do it. Also read R tags & its values.

def slurper = new XmlSlurper()
File f = new File(‘File path’)
def xml = slurper.parse(f)
def report = xml.depthFirst().findAll { it.name() == ‘reports’ }

Thanks.

XMLSlurper? For what it’s worth, you’re doing what I would do.

Thanks for reply. Do you know a way to read each R tags and its values.

hi,

regex will do that

could you share this xml as txt hard to cp text from image :slight_smile:

hi,

ok this java code will do something

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class ReadXML {

    public static void main(String argv[]) {
        try {
            File fXmlFile = new File("C:\\Users\\fitim\\IdeaProjects\\compareMaps\\src\\main\\java\\stuff.xml");
            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 nList = doc.getElementsByTagName("report");

            List<String> r4 = new ArrayList<>();
            List<String> r5 = new ArrayList<>();
            List<String> r6 = new ArrayList<>();
            List<String> r7 = new ArrayList<>();

            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                System.out.println("\nCurrent Element :" + nNode.getNodeName());
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    System.out.println("R4 : " + eElement.getElementsByTagName("R4").item(0).getTextContent());
                    r4.add(eElement.getElementsByTagName("R4").item(0).getTextContent());
                    System.out.println("R5 : " + eElement.getElementsByTagName("R5").item(0).getTextContent());
                    r5.add(eElement.getElementsByTagName("R5").item(0).getTextContent());
                    System.out.println("R6 : " + eElement.getElementsByTagName("R6").item(0).getTextContent());
                    r6.add(eElement.getElementsByTagName("R6").item(0).getTextContent());
                    System.out.println("R7 : " + eElement.getElementsByTagName("R7").item(0).getTextContent());
                    r7.add(eElement.getElementsByTagName("R7").item(0).getTextContent());
                }
            }
            int nodeR4 = 0;
            System.out.println(r4);
            for(String s : r4){
                nodeR4 += Integer.valueOf(s);
            }
            System.out.println("NODE4 sum: "+nodeR4);

            int nodeR5 = 0;
            System.out.println(r5);
            for(String s : r5){
                nodeR5 += Integer.valueOf(s);
            }
            System.out.println("NODE5 sum: "+nodeR5);

            int nodeR6 = 0;
            System.out.println(r6);
            for(String s : r6){
                nodeR6 += Integer.valueOf(s);
            }
            System.out.println("NODE6 sum: "+nodeR6);

            int nodeR7 = 0;
            System.out.println(r7);
            for(String s : r7){
                nodeR7 += Integer.valueOf(s);
            }
            System.out.println("NODE7 sum: "+nodeR7);

            int sum = nodeR4+nodeR5+nodeR6+nodeR7;
            System.out.println("nodes SUM: "+sum);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Root element :transmission

Current Element :report
R4 : 3
R5 : 10
R6 : 14
R7 : 15

Current Element :report
R4 : 2
R5 : 4
R6 : 8
R7 : 19

Current Element :report
R4 : 5
R5 : 7
R6 : 4
R7 : 3
[3, 2, 5]
NODE4 sum: 10
[10, 4, 7]
NODE5 sum: 21
[14, 8, 4]
NODE6 sum: 26
[15, 19, 3]
NODE7 sum: 37
nodes SUM: 94

@thushar.ameen

I extended your code which uses XmlSlurper.

import java.nio.file.Path
import java.nio.file.Paths

import com.kms.katalon.core.configuration.RunConfiguration
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI

Path file = Paths.get(RunConfiguration.getProjectDir())
					.resolve("Include/features/transmissions.xml")

def slurper = new XmlSlurper()
def xml = slurper.parse(file.toFile())
def reportElementList = xml.depthFirst().findAll {
	it.name() == 'report'
} 
println "number of <report> element: " + reportElementList.size()

reportElementList.each { rp ->
	println "R4: ${rp.R4}"
	println "R5: ${rp.R5}"
	println "R6: ${rp.R6}"
	println "R7: ${rp.R7}"
	println "R10: ${rp.R10}"
}

I got this output:

number of <report> element: 3
2020-03-21 20:25:33.188 DEBUG testcase.TC1                             - 6: reportElementList.each({ java.lang.Object rp -> ... })
R4: 
R5: 1930
R6: 3831
R7: Company Name
R10: Address
R4: 
R5: 1930
R6: 3831
R7: Company Name
R10: Address
R4: 
R5: 1930
R6: 3831
R7: Company Name
R10: Address

You can find a lot more of XmlSlurper usage at

1 Like

Thank you @Timo_Kuisma1

Hi,

do you need that is read as dynamic way, do not depend on is there value in R tag or is value digit or is value charts and count of R tags could be any (but count of R tags should be even in every node)

hello,
here is read as dynamic way

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

import org.apache.commons.lang3.math.NumberUtils
import org.w3c.dom.*;

try {

	String xmlFilePath = System.getProperty("user.dir")+"\\Include\\xmlFiles\\stuff.xml";
	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	Document doc = dBuilder.parse(xmlFilePath);
	doc.getDocumentElement().normalize();
	System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
	NodeList nList = doc.getElementsByTagName("report");

	int cntNlist = nList.getLength();
	int tagCounter = 0;
	DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
	Document document = docBuilder.parse(xmlFilePath);


	List<String> tags = new ArrayList<>();
	NodeList nodeList = document.getElementsByTagName("*");
	//get count of R tag names in a node
	int countReport = 0;
	for(int i = 0; i < nodeList.getLength(); i++){
		Node node = nodeList.item(i);
		if (node.getNodeType() == Node.ELEMENT_NODE) {
			if (node.getNodeName().equals("report")){
				countReport++;
			}
			if (node.getNodeName().contains("R")){
				tags.add(node.getNodeName());
				tagCounter++;
			}
			if(countReport > 1){
				break;
			}
			//System.out.println(node.getNodeName());
		}

	}

	//dynamic list for tag values
	HashMap<String,ArrayList<String>> maps1 = new HashMap<String, ArrayList<String>>();
	String tag = tags.get(0);
	String latest = tags.get(tags.size() - 1);
	latest = latest.replace("R","");
	int latestTag = Integer.parseInt(latest);
	tag = tag.replace("R","");
	int startTag = Integer.parseInt(tag);
	for (int i = 0; i <= tagCounter-1; i++) {
		maps1.put("r" + startTag, new ArrayList<>());
		startTag++;
	}

	startTag = Integer.parseInt(tag);
	//get R values from xml
	for (int temp = 0; temp < nList.getLength(); temp++) {
		Node nNode = nList.item(temp);
		//System.out.println("\nCurrent Element :" + nNode.getNodeName());
		if (nNode.getNodeType() == Node.ELEMENT_NODE) {

			Element eElement = (Element) nNode;
			for (int i = 0; i <= tagCounter-1; i++) {
				maps1.get("r" + startTag).add(eElement.getElementsByTagName("R" + startTag).item(0).getTextContent());
				startTag++;
				if (startTag >= latestTag + 1) {
					startTag = Integer.parseInt(tag);
				}
			}
		}
	}
	
	startTag = Integer.parseInt(tag);
	//TODO print out and calculate
	HashMap<Integer,ArrayList<Integer>> maps2 = new HashMap<Integer, ArrayList<Integer>>();
	for (int i = 0; i <= tagCounter-1; i++){
		maps2.put(startTag, new ArrayList<>());
		startTag++;
	}
            //add maps1 values to maps2 as integer
            startTag = Integer.parseInt(tag);
            //String val = maps1.get("r"+startTag).get(0);
            for (int i = 0; i < nList.getLength(); i++){

                for (int j = 0; j <= tagCounter-1; j++) {

                    boolean digits = NumberUtils.isDigits(maps1.get("r" + startTag).get(i));

                    if (maps1.get("r"+startTag).get(i).equals("") || digits == false){
                        maps2.get(startTag).add(0);
                        //maps2.get(startTag).add(Integer.parseInt(maps1.get("r" + startTag).get(0)));
                    }
                    else{
                        maps2.get(startTag).add(Integer.parseInt(maps1.get("r" + startTag).get(i)));
                    }
                    startTag++;
                    if (startTag >= latestTag + 1) {
                        startTag = Integer.parseInt(tag);
                    }
                }
            }
			
            startTag = Integer.parseInt(tag);
            System.out.println("Node values");
            int sumCounter = 1;
            int nodesSum = 0;
            int getCounter = 0;
            int tempSum = 0;
            for (int i = 0; i < nList.getLength(); i++) {
                for (int j = 0; j <= tagCounter-1; j++) {
                    if (maps2.get(startTag).get(i) != 0) {
                        nodesSum += maps2.get(startTag).get(i);
                        tempSum += maps2.get(startTag).get(i);
                    }
                    else{
                        nodesSum += 0;
                        tempSum += 0;
                        System.out.println("node R"+startTag+ " value: "+maps1.get("r"+startTag).get(getCounter));

                    }
                    //System.out.println("node R"+startTag+ " sum: "+nodesSum);
                    System.out.println("node R"+startTag+ " value: "+maps2.get(startTag).get(getCounter));
                    //System.out.println("node R"+startTag+ " value: "+maps1.get(startTag).get(0));
                    if (sumCounter % tagCounter == 0){
                        System.out.println("nodes sum: "+nodesSum);
                        getCounter++;
                        nodesSum = 0;
                    }
                    startTag++;
                    if (startTag >= latestTag + 1) {
                        startTag = Integer.parseInt(tag);
                    }
                    sumCounter++;
                }
            }

            System.out.println("R Node sum values: "+tempSum);

} catch (Exception e) {
	e.printStackTrace();
}

node R4 value: cat4
node R4 value: 0
node R5 value: 2
node R6 value: 3
node R7 value: 4
node R8 value: 5
node R9 value:
node R9 value: 0

nodes sum: 14

node R4 value: 1
node R5 value: 2
node R7 value: 4
node R8 value: 5
node R9 value:
node R9 value: 0

nodes sum: 15

node R4 value: 1
node R5 value: dog
node R5 value: 0
node R6 value: 3
node R7 value: 4
node R8 value: 5
node R9 value: 6

nodes sum: 19

R Node sum values: 48

Hi Timo, I want to read R tags under every report element dynamically.Not hard coded. R tags can be dynamic in every run. I don’t know what is there in the next run. In VB I used it as below,

Dim status,var_OutboundClaimNumber

Set xmlDoc = CreateObject("Msxml2.DOMDocument")
    
    xmlDoc.load(XML file path))  		 
			
	Set ElemList = xmlDoc.getElementsByTagName("report")
	counter = ElemList.length
	
			
	For r = 0 To counter-1 Step 1
	
		var_OutboundClaimNumber = ElemList.item(r).selectSingleNode("R15").text
									 
			  
			  Set ChildNodes = ElemList.item(r).childNodes
			  totalNodeCount = ChildNodes.length
			  
			  ReDim arrayOfOutboundXML(totalNodeCount,2)
			   
			  
			  
	    InboundXMLFileValidation
		
	Next
hi,

test data was
<?xml version="1.0"?>
<transmission>
    <reports>
        <report>
            <R4>cat4</R4>
            <R5>2</R5>
            <R6>3</R6>
            <R7>4</R7>
            <R8>5</R8>
            <R9></R9>
        </report>
        <report>
            <R4>1</R4>
            <R5>2</R5>
            <R6>3</R6>
            <R7>4</R7>
            <R8>5</R8>
            <R9></R9>
        </report>
        <report>
            <R4>1</R4>
            <R5>dog</R5>
            <R6>3</R6>
            <R7>4</R7>
            <R8>5</R8>
            <R9>6</R9>
        </report>
    </reports>
</transmission>

@kazurayam, Thanks for your reply. Really appreciated. I was going through the url you gave me to find reading R tags dynamically rather than hard coded. But still no luck.

Below tutorial helps