I have been looking at this code for hours and I can't make it work, and I don't know why.
var libxmljs = require("libxmljs");
var xml = '<?xml version="1.0" encoding="UTF-8"?>' +
'<root>' +
'<child foo="bar">' +
'<grandchild>First Child</grandchild>' +
'</child>' +
'<child foo="bar">' +
'<grandchild>Second child</grandchild>' +
'</child>' +
'<child foo="bar">' +
'<grandchild>Third Child</grandchild>' +
'</child>' +
'<sibling>with content!</sibling>' +
'</root>';
var xmlDoc = libxmljs.parseXml(xml);
var childs = xmlDoc.find('//child');
for (var i = 0; i < childs.length; i++)
console.log(childs[i].get('//grandchild').text());
What I expect is to get in console
First Child Second Child Third Child
But what I got is:
First Child First Child First Child
I have discovered that .get('//grandchild') returns all grandchilds in the code, despite it being called from just a node. I can't use it with an index because in my actual XML every node can have differents childs.
Thanks!
You want relative XPaths.
for (var i = 0; i < childs.length; i++)
console.log(childs[i].get('.//grandchild').text());
//---------------------------^