Express XML Body Parser

2.0.5 · active · verified Tue Apr 21

`body-parser-xml` is an Express.js middleware that extends the widely used `body-parser` library, enabling applications to seamlessly parse incoming XML-formatted request bodies into JavaScript objects. Currently at stable version 2.0.5, this package integrates an `xml` method directly onto the `body-parser` object, allowing developers to handle XML APIs while working with familiar JSON-like structures. Its release cadence reflects active maintenance, with recent updates addressing Node.js version compatibility (supporting Node 10 and above) and critical security vulnerabilities, including prototype pollution and `xml2js` dependency issues. A key differentiator is its straightforward integration model, piggybacking on `body-parser`'s established middleware pattern and providing extensive options for XML parsing via the underlying `xml2js` library, such as `normalize` and `explicitArray`. This approach simplifies the handling of diverse XML content types in Express applications.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart initializes an Express server with `body-parser-xml` to parse incoming XML requests into JavaScript objects available on `req.body`. It demonstrates configuring the middleware with `limit` and `xmlParseOptions` and includes a sample route to process and respond to XML data.

const express = require('express');
const bodyParser = require('body-parser');

// Initialize body-parser-xml to extend body-parser
require('body-parser-xml')(bodyParser);

const app = express();

// Use the XML middleware
// It parses application/xml, text/xml, and +xml content types by default
app.use(
  bodyParser.xml({
    limit: '1MB', // Reject payload bigger than 1 MB
    xmlParseOptions: {
      normalize: true, // Trim whitespace inside text nodes
      explicitArray: false, // Prevents elements with a single child from being an array
    },
  })
);

// Define a route to handle XML POST requests
app.post('/xml-data', (req, res) => {
  if (!req.body) {
    return res.status(400).send('No XML body received.');
  }
  console.log('Received XML data:', JSON.stringify(req.body, null, 2));
  res.json({ message: 'XML data received and parsed', data: req.body });
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
  console.log('Send a POST request with Content-Type: application/xml to http://localhost:3000/xml-data');
  console.log('Example cURL:');
  console.log(`curl -X POST -H "Content-Type: application/xml" -d '<root><item>Hello</item><value>123</value></root>' http://localhost:3000/xml-data`);
});

view raw JSON →