Page 1 of 1

loop xml nodes?

Posted: Wed Sep 09, 2020 10:12 am
by automation
I have this XML. How can I loop the XML and get all values in <code>?

Code: Select all

<?xml version="1.0" encoding="UTF-8"?>
<Orders>
	<Order>
		<Product>
			<Line_Id>1</Line_Id>
			<Product_Id>9831</Product_Id>
			<Name>Pontus</Name>
			<Qty>1</Qty>
			<code>AAAAA</code>
		</Product>
		<Product>
			<Line_Id>2</Line_Id>
			<Product_Id>9831</Product_Id>
			<Name>Pontus</Name>
			<Qty>1</Qty>
			<code>BBBBB</code>
		</Product>
	</Order>
</Orders>
My code. I get the first log from nodeList but not my second log "code".

Code: Select all

var dataset = job.getDataset("Xml");
var xml = new Document(dataset.getPath());

var nodeList = xml.evalToNodes("/Orders/Order/Products/Product");

s.log(1, "Found: " + nodeList.length); //This works


for(var i = 1; i < nodeList.length + 1; i++){
	var node = nodeList.at(i);
	var code = node.getValue(); //This is not working
	s.log(1, code);
}
Expected result in log
AAAAA
BBBBB
I don't get any suggestions when I write a dot (.) after "node" and get the error getValue(); is not a function.

Re: loop xml nodes?

Posted: Wed Sep 09, 2020 10:43 am
by jan_suhr
You have to run an XSLT with Saxonica that splits the XML in to one XML per node you want to use.

Re: loop xml nodes?

Posted: Wed Sep 09, 2020 11:00 am
by mkayyyy
To get to the "code" nodes you need to use this Xpath expression:

Code: Select all

/Orders/Order/Product/code
Then to loop through them your for loop needs to start from 0 and you need to use the getFirstChild() function to be able to get to the value of the node. See below code that loops through logs the "code" nodes:

Code: Select all

var dataset = job.getDataset("Xml");
var xml = new Document(dataset.getPath());

var nodeList = xml.evalToNodes("/Orders/Order/Product/code");

s.log(1, "Found: " + nodeList.length); //This works

for (var i = 0; i < nodeList.length; i++) {
	var node = nodeList.at(i);
	var code = node.getFirstChild().getValue(); //This is not working
	s.log(1, code);
}

Re: loop xml nodes?

Posted: Wed Sep 09, 2020 11:29 am
by automation
mkayyyy wrote: Wed Sep 09, 2020 11:00 am To get to the "code" nodes you need to use this Xpath expression:

Code: Select all

/Orders/Order/Product/code
Then to loop through them your for loop needs to start from 0 and you need to use the getFirstChild() function to be able to get to the value of the node. See below code that loops through logs the "code" nodes:

Code: Select all

var dataset = job.getDataset("Xml");
var xml = new Document(dataset.getPath());

var nodeList = xml.evalToNodes("/Orders/Order/Product/code");

s.log(1, "Found: " + nodeList.length); //This works

for (var i = 0; i < nodeList.length; i++) {
	var node = nodeList.at(i);
	var code = node.getFirstChild().getValue(); //This is not working
	s.log(1, code);
}
Thanks it worked!