在一個專案中,用到nodejs模組xml2js解析xml,xml的資料如下:

  1. <xml>
  2. <MsgId>6197906553041859764</MsgId>
  3. </xml>

用xml2js中的xml2js.parseString 方法解析,本來以為是一個json,但總是解析失敗,把解析的結果log下後如下:

  1. { xml: { MsgId: [ '6197906553041859764' ] } }

本來xml中<MsgId>包的是一個字串,結果解析出來的是陣列。

後來查了xml2js的官網,發現瞭如下的引數:

  1. 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的引數如下:

  1. xml2js.parseString(buf, {explicitArray : false}, function(err, json) {
  2.  
  3. });

修改後解析如下的結果如下:

  1. { xml: { MsgId: '6197906553041859764' } }

現在就變成一個字串了。

【作者】曾健生

【QQ】190678908

【app後端qq群】254659220 

【微信公眾號】 appbackend

【新浪微博】 @newjueqi

【部落格】http://blog.csdn.net/newjueqi


版權宣告:本文為博主原創文章,未經博主允許不得轉載。