如何从nodeJS中的XML解析器获取数据

时间:2017-01-07 00:31:24

标签: javascript node.js xml

我尝试使用nodeJS来访问我的代码中存储为字符串的XML中的所有数据。实际上,当我想要更深入时,我成功只能访问主节点,但不能访问所有孩子。

这是我的代码,我尝试以ms:IDENT节点获取所有数据。

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);
  });
});

感谢您提前提供任何帮助

1 个答案:

答案 0 :(得分:0)

使用xml2jsexplicitArray option默认为true,因此所有子节点都将位于数组中。

您可以像这样访问您感兴趣的值(请注意,不需要第二次调用parseString):

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);
});

如果将explicitArray指定为false,则只有在有多个子节点时才会使用数组:

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);
});