2

我有一个数据源,它只能以 XML 格式而不是 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 格式发布时,它工作得很好。

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

4

1 回答 1

0

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

于 2013-04-15T12:49:31.670 回答