I have an XML data and to read I am using 'xpath' and 'xmldom'. I am fetching relativePath
value but it's giving only first value(/abc/
) 3 times. I am not able to get other value.
var xpath = require('xpath')
var dom = require('xmldom').DOMParser
var le = `
<content>
<data>
<content-item>
<relativePath>/abc/</relativePath>
<text>abc</text>
<leaf>false</leaf>
<lastModified>2018-10-16</lastModified>
</content-item>
<content-item>
<relativePath>/defghi/</relativePath>
<text>defghi</text>
<leaf>false</leaf>
<lastModified>2018-06-23</lastModified>
</content-item>
<content-item>
<relativePath>/jklmn/</relativePath>
<text>jklmn</text>
<leaf>false</leaf>
<lastModified>2019-02-27</lastModified>
</content-item>`;
var doc = new dom().parseFromString(le);
var nodes = xpath.select("//content-item", doc);
nodes.forEach( (n, i) => {
var title = xpath.select("string(//relativePath)", n);
console.log(title);
});
Final output:
/abc/
/abc/
/abc/
The problem is that you're taking the string value of a nodeset, which is by definition the string value of the first node. Iterate over the selected nodes in JavaScript, and only take the string value of each individually rather than call the XPath string()
function on the entire nodeset collectively.
It's also unclear why you'd want a nested loop rather than a single loop over all relativePath
elements, but perhaps that was an artifact of the reduction of your complete program to a posted example. In any case, if you wish to restrict your inner loop to only those relativePath
elements beneath the current content-item
context node, use .//relativePath
instead.
Finally, your XML is not well-formed.
I've fixed the above problems in the example below (and indented the XML to ease reading):
var xpath = require('xpath')
var dom = require('xmldom').DOMParser
var le = `
<content>
<data>
<content-item>
<relativePath>/abc/</relativePath>
<text>abc</text>
<leaf>false</leaf>
<lastModified>2018-10-16</lastModified>
</content-item>
<content-item>
<relativePath>/defghi/</relativePath>
<text>defghi</text>
<leaf>false</leaf>
<lastModified>2018-06-23</lastModified>
</content-item>
<content-item>
<relativePath>/jklmn/</relativePath>
<text>jklmn</text>
<leaf>false</leaf>
<lastModified>2019-02-27</lastModified>
</content-item>
</data>
</content>`;
var doc = new dom().parseFromString(le);
var nodes = xpath.select("//relativePath", doc);
nodes.forEach( (n, i) => {
console.log(n.textContent);
});
/abc/
/defghi/
/jklmn/
as requested.