[英]Unable to parse XML with NodeJS (ExpressJS) for entry into MongoDB
我有一個僅以XML格式而不是JSON可用的數據源,JSON是MongoDB的首選數據類型。 我有一種方法允許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格式發布時,效果很好。
任何建議將不勝感激,謝謝!
查看xmlParser中間件: https : //github.com/brandid/express-xmlBodyParser
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.