Reputation: 67
I try to use nodeJS to get access to all data from an XML stored as a string in my code for now. Actually, I succeeded only getting access to the main node but not all children when i wanted to get deeper.
Here is my code, and I try to get all data in ms:IDENT node.
var http = require('http');
var xml2js = require('xml2js');
var extractedData = "";
var parser = new xml2js.Parser();
var xml = "<wfs:FeatureCollection><gml:boundedBy><gml:Box srsName='EPSG:3945'><gml:coordinates>1399644.376399,4179041.966594 1426575.406024,4209057.424111</gml:coordinates></gml:Box></gml:boundedBy><gml:featureMember><ms:SV_ARRET_P fid='SV_ARRET_P.1484'><gml:boundedBy><gml:Box srsName='EPSG:3945'><gml:coordinates>1418152.331881,4208150.797551 1418152.331881,4208150.797551</gml:coordinates></gml:Box></gml:boundedBy><ms:msGeometry><gml:Point srsName='EPSG:3945'><gml:coordinates>1418152.331881,4208150.797551</gml:coordinates></gml:Point></ms:msGeometry><ms:GID>1484</ms:GID><ms:GEOM_O>196</ms:GEOM_O><ms:IDENT>FLA92A</ms:IDENT><ms:GROUPE>FLA92</ms:GROUPE><ms:LIBELLE>Fort Lajard</ms:LIBELLE><ms:TYPE>BUS</ms:TYPE><ms:CDATE>2017-01-06T14:15:10</ms:CDATE><ms:MDATE>2017-01-06T14:15:10</ms:MDATE></ms:SV_ARRET_P></gml:featureMember></wfs:FeatureCollection>"
parser.parseString(xml, function(err,result){
//Extract the value from the data element
xml = result['wfs:FeatureCollection'];
parser.parseString(xml, function(err,result){
extractedData = result['wfs:FeatureCollection']['gml:featureMember']['ms:SV_ARRET_P']['ms:IDENT'];
console.log(extractedData);
});
});
Thank you for any help in advance
Upvotes: 1
Views: 1727
Reputation: 58400
With xml2js
, the explicitArray
option defaults to true
, so all child nodes will be in an array.
You can access the value you are interested in like this (note that the second call to parseString
is not required):
var parser = new xml2js.Parser();
parser.parseString(xml, function (error, result) {
var value = result['wfs:FeatureCollection']['gml:featureMember'][0]['ms:SV_ARRET_P'][0]['ms:IDENT'][0];
console.log(value);
});
If you specify explicitArray
as false
, arrays will be used only if there are multiple child nodes:
var parser = new xml2js.Parser({ explicitArray: false });
parser.parseString(xml, function (error, result) {
var value = result['wfs:FeatureCollection']['gml:featureMember']['ms:SV_ARRET_P']['ms:IDENT'];
console.log(value);
});
Upvotes: 1