使用Node JS

时间:2016-04-21 19:50:12

标签: xml node.js rest body-parser

我在节点中编写REST服务,它以XML作为输入,但是当我解析它时,只显示第一级节点,嵌套的节点显示为对象。

我无法硬编码要读取的XML元素,因为根据规范,有可选元素,因此它必须是动态的。

我使用body-parser-xml来解析XML。

var express = require('express'),
    bodyParser = require('body-parser');

require('body-parser-xml')(bodyParser);

//var xmlparser = require('express-xml-bodyparser');

var app = express();

app.use(bodyParser.xml({
  limit: '1MB',   // Reject payload bigger than 1 MB 
  xmlParseOptions: {
    normalize: true,     // Trim whitespace inside text nodes 
    normalizeTags: true, // Transform tags to lowercase 
    explicitArray: false, // Only put nodes in array if >1 
    preserveChildrenOrder: true
  }
}));

// app.use(xmlparser());

app.post('/users', function(req, res, body) {
  // Any request with an XML payload will be parsed 
  // and a JavaScript object produced on req.body 
  // corresponding to the request payload. 
  console.log(req.body);
  var parsedXml = req.body;
  console.log(parsedXml.classes);
  res.status(200).end();
});

var http = require('http');
http.createServer(app).listen(3000);

我的REST XML输入是

<?xml version="1.0" encoding="UTF-8"?>
<Schools>
<School>
    <Name>Some Name</Name>
    <City>Some City</City>
    <Classes>
        <Class>
            <Name>Class 1</Name>
            <OnRoll>20</OnRoll>
            <Students>
                <Student>
                    <Name>Student 1</Name>
                    <Age>10</Age>
                </Student>
                <Student>
                    <Name>Student 2</Name>
                    <Age>11</Age>
                </Student>
            </Students>
        </Class>
        <Class>
            <Name>Class 2</Name>
            <OnRoll>30</OnRoll>
            <Students>
                <Student>
                    <Name>Student 21</Name>
                    <Age>12</Age>
                </Student>
                <Student>
                    <Name>Student 22</Name>
                    <Age>13</Age>
                </Student>
            </Students>
        </Class>
    </Classes>
    <Labs>
        <Lab>
            <Name>Science Lab 1</Name>
            <Subject>Physics</Subject>
        </Lab>
        <Lab>
            <Name>Science Lab 2</Name>
            <Subject>Chemistry</Subject>
        </Lab>
    </Labs>
    </School>
</Schools>

输出

D:\Tryouts\myapp>node xmlParser.js
{ schools:
   { school:
      { name: 'Some Name',
        city: 'Some City',
        classes: [Object],
        labs: [Object] } } }
undefined

基本上我正在查看会自动读取嵌套XML并显示它的内容。

我使用Chrome REST插件调用此服务http://localhost:3000/usersMethodPOSTContent-Typeapplication/xml

请求您的帮助以解决此问题。

1 个答案:

答案 0 :(得分:2)

您可能想要使用好的Util包。试试这个:

const util = require('util');
// Parse your xml file   
console.log(util.inspect(parsedXml.classes, { depth: null, showHidden: false }));

希望这有帮助。