X Xerobit

XML vs JSON in API Design — When to Choose Each Format

JSON has largely replaced XML in REST APIs, but XML still dominates in SOAP, enterprise integrations, RSS/Atom, and SVG. Learn when to use XML vs JSON, content negotiation, and...

Mian Ali Khalid · · 5 min read
Use the tool
XML Formatter
Format, validate, and beautify XML documents.
Open XML Formatter →

JSON won the REST API format war, but XML remains essential for SOAP, enterprise middleware, RSS feeds, configuration files, and SVG. Here’s when each format is the right choice and how to support both.

Use the XML Formatter to format and validate XML responses.

When JSON wins

{
  "user": {
    "id": 123,
    "name": "Alice",
    "roles": ["admin", "editor"],
    "metadata": { "lastLogin": "2026-05-11" }
  }
}

JSON advantages:

  • Native JavaScript parsing (JSON.parse)
  • Smaller payloads (no closing tags)
  • Direct array support
  • Widespread browser and server support
  • All modern REST frameworks produce it by default

Use JSON for:

  • REST APIs with JavaScript/mobile clients
  • Configuration files (package.json, tsconfig.json)
  • Message queues and event streams
  • Internal microservice communication

When XML is required or preferred

<user id="123">
  <name>Alice</name>
  <roles>
    <role>admin</role>
    <role>editor</role>
  </roles>
  <metadata>
    <lastLogin>2026-05-11</lastLogin>
  </metadata>
</user>

XML advantages:

  • Attributes AND element content (more expressive)
  • Comments in the data
  • Namespaces (avoid naming conflicts across systems)
  • Schema validation (XSD, DTD, RelaxNG)
  • XSLT transformation
  • XPath querying

XML is required for:

  • SOAP web services (still dominant in banking, healthcare, government)
  • RSS/Atom feeds
  • WSDL service descriptions
  • Android layouts (res/layout/*.xml)
  • Maven/Gradle build files
  • SVG and MathML
  • Microsoft Office Open XML (.docx, .xlsx)
  • DocBook and DITA documentation
  • XML-RPC (older RPC standard)

Content negotiation — support both

HTTP content negotiation lets clients request JSON or XML:

// Express: serve JSON or XML based on Accept header
import { create } from 'xmlbuilder2';

app.get('/api/users/:id', async (req, res) => {
  const user = await db.users.findById(req.params.id);
  const accepts = req.accepts(['application/json', 'application/xml']);
  
  if (accepts === 'application/xml') {
    const xml = create({ version: '1.0' })
      .ele('user', { id: user.id })
        .ele('name').txt(user.name).up()
        .ele('email').txt(user.email).up()
      .end({ prettyPrint: true });
    
    return res.type('application/xml').send(xml);
  }
  
  // Default: JSON
  res.json(user);
});
# Client requests XML:
curl -H "Accept: application/xml" https://api.example.com/users/123

# Client requests JSON:
curl -H "Accept: application/json" https://api.example.com/users/123

Converting between formats in Node.js

// JSON → XML using xmlbuilder2:
import { create } from 'xmlbuilder2'; // npm install xmlbuilder2

function jsonToXml(obj, rootElement = 'root') {
  const doc = create({ version: '1.0' }).ele(rootElement);
  
  function addNode(parent, key, value) {
    if (Array.isArray(value)) {
      value.forEach(item => addNode(parent, key, item));
    } else if (typeof value === 'object' && value !== null) {
      const child = parent.ele(key);
      Object.entries(value).forEach(([k, v]) => addNode(child, k, v));
    } else {
      parent.ele(key).txt(String(value));
    }
  }
  
  Object.entries(obj).forEach(([k, v]) => addNode(doc, k, v));
  return doc.end({ prettyPrint: true });
}

// XML → JSON using fast-xml-parser:
import { XMLParser } from 'fast-xml-parser'; // npm install fast-xml-parser

const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@_' });

function xmlToJson(xmlString) {
  return parser.parse(xmlString);
}

SOAP envelope example

SOAP still heavily used in enterprise integrations:

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope
  xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  
  <soap:Header>
    <wsse:Security xmlns:wsse="...">
      <wsse:UsernameToken>
        <wsse:Username>user@example.com</wsse:Username>
        <wsse:Password>password</wsse:Password>
      </wsse:UsernameToken>
    </wsse:Security>
  </soap:Header>
  
  <soap:Body>
    <GetUserRequest xmlns="https://api.example.com/users">
      <UserId>123</UserId>
    </GetUserRequest>
  </soap:Body>
  
</soap:Envelope>

No JSON equivalent can carry the authentication, namespacing, and data in a standardized envelope structure that SOAP provides — hence its persistence in legacy enterprise systems.


Related posts

Related tool

XML Formatter

Format, validate, and beautify XML documents.

Written by Mian Ali Khalid. Part of the Dev Productivity pillar.