源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

实例分析nodejs模块xml2js解析xml过程中遇到的坑

  • 时间:2022-01-21 17:57 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:实例分析nodejs模块xml2js解析xml过程中遇到的坑
本文实例讲述了nodejs模块xml2js解析xml过程中遇到的坑。分享给大家供大家参考,具体如下: 在一个项目中,用到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' } }

现在就变成一个字符串了。 [b]PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:[/b] [b]在线XML/JSON互相转换工具: [/b][url=http://tools.jb51.net/code/xmljson]http://tools.jb51.net/code/xmljson[/url] [b]在线格式化XML/在线压缩XML: [/b][url=http://tools.jb51.net/code/xmlformat]http://tools.jb51.net/code/xmlformat[/url] [b]XML[/b][b]在线压缩/格式化工具: [/b][url=http://tools.jb51.net/code/xml_format_compress]http://tools.jb51.net/code/xml_format_compress[/url] [b]XML[/b][b]代码在线格式化美化工具: [/b][url=http://tools.jb51.net/code/xmlcodeformat]http://tools.jb51.net/code/xmlcodeformat[/url] 希望本文所述对大家nodejs程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部