无法使用NodeJS(ExpressJS)parsingXML以进入MongoDB

我有一个数据源只能以XML格式提供给我,而不是JSON,这是MongoDB的首选数据types。 我有一个方法,允许JSON发布到MongoDB集合,我试图修改它来处理XML数据。

这是我修改的方法:

exports.addXMLTicket = function(req, res) { var xml2js = require('xml2js'); var xml = req.body; var parser = new xml2js.Parser(); parser.parseString(xml, function (err, ticket) { console.log('Done parsing XML'); console.log('Adding ticket: ' + JSON.stringify(ticket)); db.collection('tickets', function(err, collection) { collection.insert(ticket, {safe:true}, function(err, result) { if (err) { res.send({'error':'An error has occurred'}); } else { console.log('Success: ' + JSON.stringify(result[0])); res.send(result[0]); } }); }); }); } 

这里是XML数据:

 <?xml version='1.0'?> <instance dm:form_version='1.0' dm:submit_time='2012-04-02 12:33:26 UTC' dm:submitting_user='Dusan Babich' writeTime='2011-04-26T15:23:11.506' dm:form='A First Form' dm:submitting_device='iPhone_d6e2542effafbcc8d0e6bf0ef2917b76dea4faf8' xmlns:dm='http://mobileforms.devicemagic.com/xforms' xmlns='http://www.devicemagic.com/xforms/demo/2d3698c0-650c-012e-7e8e-12313b079c72'> <untitled_form_1> <quality_of_day>{{VALUE}}</quality_of_day> <inbox_overflow>{{VALUE}}</inbox_overflow> <next_holiday>{{VALUE}}</next_holiday> <comments>{{VALUE}}</comments> </untitled_form_1> </instance> 

最后我的CURL请求:

 curl -i -X POST -H "Content-Type: text/xml" -d "<?xml version='1.0'?><instance dm:form_version='1.0' dm:submit_time='2012-04-02 12:33:26 UTC' dm:submitting_user='Dusan Babich' writeTime='2011-04-26T15:23:11.506' dm:form='A First Form' dm:submitting_device='iPhone_d6e2542effafbcc8d0e6bf0ef2917b76dea4faf8' xmlns:dm='http://mobileforms.testdomain.com/xforms' xmlns='http://www.testdomain.com/xforms/demo/2d3698c0-650c-012e-7e8e-12313b079c72'><untitled_form_1><quality_of_day>test</quality_of_day><inbox_overflow>test</inbox_overflow><next_holiday>test</next_holiday><comments>test</comments></untitled_form_1>" http://127.0.0.1:3000/ticketsxml 

有错误,我得到的是,“TypeError:不能读取属性'_id'的未定义”似乎正在发生,因为它没有从POST获取正文。 但是,当我发布在JSON格式它工作得很好。

任何build议将不胜感激,谢谢!

查看xmlParser中间件: https : //github.com/brandid/express-xmlBodyParser