this code returns content only if I type last xml's element's ID. I want to content and page be loaded when I type any of element's ID. How to do that?
var libxmljs = require("libxmljs");
var xml = ('/Path/Apples.xml');
fs.readFile(__dirname + '/Apples.xml', function (err, data) {
var xmlStr = data.toString();
var xmlDoc2 = libxmljs.parseXmlString(xmlStr);
var Apple = xmlDoc2.get('Apples').childNodes();
for (var i = 0; i < Apple.length; i++) {
var nameattr = xmlDoc2.get('Apples').get('Apple').attr('id').value();
var AppleId = Apple[i].attr('id');
if (AppleId !== null) {
var AppleIdVal = AppleId.value();
console.log('somename ' + AppleIdVal);
app.get('/obj/:id', function (req, res) {
if (req.params.id == AppleIdVal) {
console.log('nameAttr: ' + AppleIdVal);
res.json('This is id: ' + AppleIdVal);
}
});
}
}
Only function closures can capture current variable values like that, not if () {} blocks. Also, you're currently adding a bunch of duplicate routes every time AppleId is not null. Consider rewriting your logic, for example:
var libxmljs = require('libxmljs');
var xmlDoc2, Apple;
fs.readFile(__dirname + '/Apples.xml', function(err, data) {
xmlDoc2 = libxmljs.parseXmlString(data.toString());
Apple = xmlDoc2.get('Apples').childNodes();
// move your `app.listen()` here instead so that the file will have been read
// before processing any requests
});
app.get('/obj/:id', function (req, res) {
for (var i = 0; i < Apple.length; i++) {
var nameattr = xmlDoc2.get('Apples').get('Apple').attr('id').value(),
AppleId = Apple[i].attr('id');
if (AppleId !== null) {
var AppleIdVal = AppleId.value();
if (req.params.id == AppleIdVal)
return res.json('This is id: ' + AppleIdVal);
}
}
res.json('id not found');
});
Additionally, you may consider swapping out the for-loop for code that does a single xpath lookup to find the id.