Node + Express: How to Return XML Response

Last updated on July 17, 2021 A Goodman Loading... Post a comment

This article walks you through a few examples of responding in XML when using Express and Node.js. Besides express, we don’t need any other npm libraries.

Example 1: Basic

This example creates a list of fiction products and returns it in XML format instead of JSON.

The complete code

// index.js
const express = require("express");
const xml = require("xml");

const app = express();
app.get("/", (req, res, next) => {
  let data = `<?xml version="1.0" encoding="UTF-8"?>`;
  data += `<products>`;

  for (let i = 0; i < 100; i++) {
    data += `<item> 
       <name>Product ${i}</name>
       <price>${i}</price>
    </item>`;
  }

  data += `</products>`;

  res.header("Content-Type", "application/xml");
  res.status(200).send(data);
});

app.listen(3000, () => {
  console.log("Server is running on port 3000");
});

// kindacode.com

Run it:

node index.js 

Or:

nodemon index.js

Check The Result

Open your web browser and navigate to http://localhost:3000 then you’ll see something like this:

Example 2: Making a XML Sitemap

This example is a real-world use case: making an XML sitemap.

The code

const express = require("express");
const xml = require("xml");

const app = express();
app.get("/sitemap.xml", (req, res, next) => {
  let data = `<?xml version="1.0" encoding="UTF-8"?>
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  `;

  const urls = [];
  urls.push(`<url>
                <loc>https://www.kindacode.com</loc>
                <changefreq>dailly</changefreq>
                <priority>1.0</priority>
            </url>`);

  // Fetch your urls from database or somewhere else
  // The add to the urls array
  for (let i = 0; i < 100; i++) {
    urls.push(`<url>
              <loc>https://www.kindacode.com/demo/${i}</loc>
              <lastmod>2021-07-27T19:34:00+01:00</lastmod>
              <changefreq>weekly</changefreq>
              <priority>0.8</priority>
          </url>`);
  }

  data += urls.join("/n");
  data += `</urlset>`;

  res.header("Content-Type", "application/xml");
  res.status(200).send(data);
});

app.listen(3000, () => {
  console.log("Server is running on port 3000");
});

Output

Open your web browser and navigate to http://localhost/sitemap.xml. You should see something like this:

Conclusion

We’ve examined a couple of examples of responding XML data using Node.js and Express.js. If you’d like to explore more modern and fascinating stuff about backend development with Javascript, take a look at the following articles:

You can also check out our Node.js category page or PHP category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles