-
automation
- Member
- Posts: 30
- Joined: Tue Jan 15, 2019 10:19 pm
Post
by automation » Wed Sep 09, 2020 10:12 am
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.
-
jan_suhr
- Advanced member
- Posts: 408
- Joined: Fri Nov 04, 2011 1:12 pm
- Location: Nyköping, Sweden
Post
by jan_suhr » Wed Sep 09, 2020 10:43 am
You have to run an XSLT with Saxonica that splits the XML in to one XML per node you want to use.
-
mkayyyy
- Member
- Posts: 36
- Joined: Mon Nov 21, 2016 6:31 pm
- Location: UK
Post
by mkayyyy » Wed Sep 09, 2020 11:00 am
To get to the "code" nodes you need to use this Xpath expression:
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);
}
-
automation
- Member
- Posts: 30
- Joined: Tue Jan 15, 2019 10:19 pm
Post
by automation » Wed Sep 09, 2020 11:29 am
mkayyyy wrote: ↑Wed Sep 09, 2020 11:00 am
To get to the "code" nodes you need to use this Xpath expression:
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!