node.js - Extract values from nested XML using Node JS -
i'm writing rest service in node takes xml input, when parse it, 1st level nodes displayed, nested ones displayed objects.
i cannot hard-code xml elements read because per specification there optional elements, has dynamic.
i'm using body-parser-xml
parse 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 1 mb xmlparseoptions: { normalize: true, // trim whitespace inside text nodes normalizetags: true, // transform tags lowercase explicitarray: false, // put nodes in array if >1 preservechildrenorder: true } })); // app.use(xmlparser()); app.post('/users', function(req, res, body) { // request xml payload parsed // , javascript object produced on req.body // corresponding 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);
my xml input rest
<?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>
and output
d:\tryouts\myapp>node xmlparser.js { schools: { school: { name: 'some name', city: 'some city', classes: [object], labs: [object] } } } undefined
basically i'm looking @ automatically read nested xml , display it.
i'm using chrome rest plugin invoke service http://localhost:3000/users
method
post
, content-type
application/xml
.
requesting resolve this.
you may want use , nice util
package. try this:
const util = require('util'); // parse xml file console.log(util.inspect(parsedxml.classes, { depth: null, showhidden: false }));
hope helps.
Comments
Post a Comment