Express XML Body Parser Middleware

0.4.1 · maintenance · verified Tue Apr 21

express-xml-bodyparser is a Connect/Express middleware designed to parse incoming raw XML request bodies, converting them into a JavaScript object available on `req.body`. It leverages the `xml2js` library for XML parsing. The current stable version is 0.4.1. The package has a slow release cadence, with updates typically addressing dependencies or minor fixes, rather than frequent feature additions. Key differentiators include its ability to parse data only once even if called multiple times, gracefully skip parsing for empty bodies, and accept a wide range of XML-based content-types (e.g., `application/rss+xml`). It provides custom configuration options that are merged with opinionated defaults to normalize the resulting JSON structure, such as trimming whitespace and lowercasing tag names, which users need to be aware of if they desire standard `xml2js` behavior. TypeScript type definitions are available via `@types/express-xml-bodyparser`.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart initializes an Express application, applies the xml-bodyparser middleware globally, and sets up a route to handle incoming XML requests, demonstrating how to access the parsed `req.body` and how to apply the middleware with custom `xml2js` options on specific routes.

import express from 'express';
import http from 'http';
import xmlparser from 'express-xml-bodyparser';

const app = express();
const server = http.createServer(app);

// Apply JSON and URL-encoded body parsers first if needed
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Apply the XML body parser globally
app.use(xmlparser());

app.post('/receive-xml', function(req, res, next) {
  // req.body contains the parsed XML as a JavaScript object
  console.log('Received XML body:', req.body);
  if (req.body) {
    res.status(200).json({ message: 'XML received', data: req.body });
  } else {
    res.status(400).json({ message: 'No XML body received' });
  }
});

// Example of using xmlparser on a specific route with custom options
app.post('/receive-xml-custom', xmlparser({ trim: false, explicitArray: false }), function(req, res, next) {
  console.log('Received custom XML body:', req.body);
  if (req.body) {
    res.status(200).json({ message: 'XML received with custom options', data: req.body });
  } else {
    res.status(400).json({ message: 'No XML body received' });
  }
});

const PORT = 1337;
server.listen(PORT, () => {
  console.log(`Server listening on http://localhost:${PORT}`);
  console.log('Send POST requests to /receive-xml or /receive-xml-custom with Content-Type: application/xml');
});

view raw JSON →