在一個項目中,用到nodejs模塊xml2js解析xml,xml的數據如下:
<xml> <MsgId>6197906553041859764</MsgId> </xml>
用xml2js中的xml2js.parseString 方法解析,本來以為是一個json,但總是解析失敗,把解析的結果log下后如下:
{ xml: { MsgId: [ '6197906553041859764' ] } }
本來xml中<MsgId>包的是一個字符串,結果解析出來的是數組。
后來查了xml2js的官網,發現了如下的參數:
explicitArray (default: true): Always put child nodes in an array if true; otherwise an array is created only if there is more than one.
原來xml2js默認會把子子節點的值變為一個數組,這個坑真大啊!!!為了查這個問題,花了半天的時間。
知道原因后,解決的方法也很簡單,在調用xml2js.parseString時加入explicitArray的參數如下:
xml2js.parseString(buf, {explicitArray : false}, function(err, json) { });
修改后解析如下的結果如下:
{ xml: { MsgId: '6197906553041859764' } }
現在就變成一個字符串了。
【作者】曾健生
【QQ】190678908
【app后端qq群】254659220
【微信公眾號】 appbackend
【新浪微博】 @newjueqi
【博客】http://blog.csdn.net/newjueqi
版權聲明:本文為博主原創文章,未經博主允許不得轉載。