Tutorial2024-05-20

XML to JSON and Back: The Complete Conversion Guide for Legacy Systems

Migrating from XML APIs to JSON? Or need to integrate with a legacy SOAP service? Here's everything you need to know about converting between the two.

#xml#json#conversion#api#legacy-systems

甲方说:我们的老系统用的是 XML,新系统要 JSON。你来搞定。

Sound familiar? I've done this migration 5 times in my career. Each time, someone says "it's just a format change." It's never just a format change.

Here's the complete guide to XML ↔ JSON conversion — with all the edge cases nobody warns you about.

Why Convert?

  • Legacy SOAP APIs → Modern REST APIs
  • RSS/Atom feeds → JSON feeds
  • Configuration files (XML → JSON)
  • Data migration between systems

XML to JSON: The Rules

1. Elements Become Keys

<user>
  <name>John</name>
  <age>30</age>
</user>
{ "user": { "name": "John", "age": 30 } }

2. Attributes Need Special Handling

<user id="123" role="admin">
  <name>John</name>
</user>
{ "user": { "@id": "123", "@role": "admin", "name": "John" } }

Convention: prefix attributes with @.

3. Repeated Elements Become Arrays

<users>
  <user><name>John</name></user>
  <user><name>Jane</name></user>
</users>
{ "users": { "user": [{ "name": "John" }, { "name": "Jane" }] } }

4. The Empty Element Problem

<phone></phone>  <!-- Is this null, empty string, or missing? -->

This is where conversions break. You need a convention:

  • null → element not present
  • "" → empty element
  • Or use xsi:nil="true" for explicit null

JSON to XML: The Reverse

{ "user": { "name": "John", "hobbies": ["reading", "coding"] } }
<user>
  <name>John</name>
  <hobbies>reading</hobbies>
  <hobbies>coding</hobbies>
</user>

Tools for Conversion

Use an XML to JSON Converter for quick conversions. For bulk processing, write a script:

// Node.js
const { XMLParser } = require('fast-xml-parser');
const parser = new XMLParser({ ignoreAttributes: false });
const json = parser.parse(xmlString);

Edge Cases That Will Bite You

  1. Namespaces<ns:user> becomes "ns:user" key. Handle carefully.
  2. Mixed content<p>Hello <b>world</b></p> — text + elements mixed
  3. CDATA sections<![CDATA[<xml>]]> — treat as text content
  4. Processing instructions<?xml version="1.0"?> — skip or preserve?
  5. Comments — XML comments have no JSON equivalent

The Migration Checklist

  • Map XML schema to JSON schema
  • Decide attribute handling convention (@ prefix)
  • Handle empty elements (null vs empty string)
  • Convert arrays (repeated elements)
  • Handle namespaces
  • Test with edge cases (empty, null, special chars)
  • Validate output with JSON Formatter

Convert between XML and JSON instantly with our free XML to JSON Converter — handles attributes, arrays, and namespaces automatically.

🛠

Try It Yourself

Put what you've learned into practice with our free online tools.

Explore More Developer Tools

Discover more tools and tutorials in this category

Browse Category →