DevToolBox無料
ブログ

XML vs JSON:どちらを使うべきか — 開発者向け完全比較

8分by DevToolBox

XML and JSON are the two most widely used data interchange formats in software development. While JSON has become the dominant choice for web APIs, XML remains essential in many enterprise and document-centric use cases. This guide provides a comprehensive comparison with side-by-side examples, a detailed feature table, performance benchmarks, and practical migration patterns.

Format and validate your XML instantly with our free XML Formatter tool →

Quick Answer: Which Should You Use?

Use JSON when building REST APIs, web applications, configuration files, or working with NoSQL databases. JSON is lighter, faster to parse, and natively supported in JavaScript.

Use XML when you need document markup, namespaces, schema validation, XSLT transformations, or working with enterprise systems (SOAP, RSS/Atom, SVG, XHTML). XML excels at representing mixed content and self-describing documents.

Syntax Comparison: Same Data, Two Formats

Here is the same data structure expressed in both XML and JSON:

XML

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book isbn="978-0-13-468599-1" category="programming">
    <title lang="en">The Pragmatic Programmer</title>
    <authors>
      <author>David Thomas</author>
      <author>Andrew Hunt</author>
    </authors>
    <year>2019</year>
    <price currency="USD">49.95</price>
    <inStock>true</inStock>
    <tags>
      <tag>programming</tag>
      <tag>best-practices</tag>
      <tag>career</tag>
    </tags>
  </book>
</bookstore>

JSON

{
  "bookstore": {
    "books": [
      {
        "isbn": "978-0-13-468599-1",
        "category": "programming",
        "title": "The Pragmatic Programmer",
        "titleLang": "en",
        "authors": [
          "David Thomas",
          "Andrew Hunt"
        ],
        "year": 2019,
        "price": 49.95,
        "priceCurrency": "USD",
        "inStock": true,
        "tags": ["programming", "best-practices", "career"]
      }
    ]
  }
}

Feature Comparison Table

FeatureXMLJSON
Schema ValidationYes — XSD, DTD, RelaxNG (very powerful)Yes — JSON Schema (less mature)
NamespacesYes — built-in namespace supportNo — no native namespace concept
CommentsYes — <!-- comment -->No — not allowed in standard JSON
AttributesYes — elements can have attributesNo — only key-value pairs
CDATA SectionsYes — for raw/unescaped contentNo — all strings are escaped
Query LanguageXPath, XQuery (powerful querying)JSONPath, jq (simpler)
Data SizeLarger — verbose tags add overheadSmaller — minimal syntax, less overhead
Human ReadabilityGood — self-describing tagsGood — clean, less visual noise
Parse SpeedSlower — complex DOM/SAX parsingFaster — simple grammar, native in JS
Browser SupportGood — DOMParser, XSLT processorExcellent — native JSON.parse/stringify
StreamingYes — SAX, StAX for large filesLimited — needs streaming libraries
Built-in ValidationStrong — DTD, XSD enforce structureBasic — JSON Schema is optional
TransformationXSLT — powerful transformation languageNo native equivalent — use code
Mixed ContentYes — text + elements can be interleavedNo — not designed for mixed content
MetadataProcessing instructions, attributes, commentsNo built-in metadata mechanism
Data TypesAll values are strings by defaultstring, number, boolean, null, array, object
Encoding DeclarationYes — <?xml encoding="UTF-8"?>No — assumes UTF-8
Element OrderingPreserved — order is significantObjects unordered, arrays ordered

When to Use JSON

  • REST APIs — JSON is the universal payload format for modern web APIs (fetch, Axios, GraphQL)
  • Configuration files — package.json, tsconfig.json, .eslintrc.json, composer.json
  • NoSQL databases — MongoDB, CouchDB, DynamoDB store JSON-like documents natively
  • Web applications — JavaScript/TypeScript can parse JSON natively with zero dependencies
  • Real-time data — WebSocket messages, Server-Sent Events typically use JSON
  • Mobile APIs — smaller payload size means faster transfers on mobile networks
// REST API response (JSON)
{
  "status": "success",
  "data": {
    "users": [
      { "id": 1, "name": "Alice", "email": "alice@example.com" },
      { "id": 2, "name": "Bob", "email": "bob@example.com" }
    ],
    "pagination": { "page": 1, "total": 42 }
  }
}

// package.json
{
  "name": "my-app",
  "version": "1.0.0",
  "scripts": {
    "dev": "next dev",
    "build": "next build"
  },
  "dependencies": {
    "react": "^19.0.0",
    "next": "^15.0.0"
  }
}

When to Use XML

  • SOAP web services — enterprise APIs still widely use XML-based SOAP protocols
  • RSS/Atom feeds — syndication formats are XML-based
  • SVG graphics — Scalable Vector Graphics is an XML vocabulary
  • XHTML/HTML5 — strict XHTML serialization uses XML syntax
  • Enterprise integration — healthcare (HL7/FHIR), finance (FIX, XBRL), government (UBL)
  • Document markup — DocBook, DITA, TEI for structured documents
  • Office documents — OOXML (.docx, .xlsx) and ODF (.odt) are XML-based
  • Configuration with validation — Maven pom.xml, Spring XML, Android manifests
<!-- SOAP Request -->
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetStockPrice xmlns="http://example.com/stocks">
      <StockName>GOOG</StockName>
    </GetStockPrice>
  </soap:Body>
</soap:Envelope>

<!-- RSS Feed -->
<rss version="2.0">
  <channel>
    <title>DevToolBox Blog</title>
    <link>https://viadreams.cc/en/blog</link>
    <item>
      <title>XML vs JSON Comparison</title>
      <description>Complete guide...</description>
    </item>
  </channel>
</rss>

<!-- SVG -->
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="40" fill="#3b82f6" />
  <text x="50" y="55" text-anchor="middle" fill="white">SVG</text>
</svg>

<!-- Maven pom.xml -->
<project xmlns="http://maven.apache.org/POM/4.0.0">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>my-app</artifactId>
  <version>1.0-SNAPSHOT</version>
</project>

Performance Benchmarks

Typical performance characteristics when processing the same dataset (approximate values, actual results vary by implementation and data):

MetricXMLJSON
Parse Time (1MB file)~50–80ms~15–30ms
File Size (same data)~1.0x (baseline)~0.5–0.7x
Memory Usage (DOM)~3–5x document size~2–3x document size
Serialization SpeedModerateFast (JSON.stringify)
Streaming Parse (1GB)SAX: efficient, low memoryRequires external libraries

Note: XML streaming parsers (SAX/StAX) can process very large files with constant memory. JSON streaming is possible but requires libraries like json-stream or ijson. For small payloads (<100KB), the difference is negligible.

Parsing in Different Languages

JavaScript / TypeScript

// --- JSON parsing (built-in) ---
const jsonStr = '{"name":"Alice","age":30}';
const obj = JSON.parse(jsonStr);
console.log(obj.name); // "Alice"

// Serialize back
const output = JSON.stringify(obj, null, 2);

// --- XML parsing (browser) ---
const xmlStr = '<user><name>Alice</name><age>30</age></user>';
const parser = new DOMParser();
const doc = parser.parseFromString(xmlStr, 'text/xml');
const name = doc.querySelector('name')?.textContent; // "Alice"

// --- XML parsing (Node.js with xml2js) ---
import { parseStringPromise } from 'xml2js';
const result = await parseStringPromise(xmlStr);
console.log(result.user.name[0]); // "Alice"

Python

import json
import xml.etree.ElementTree as ET

# --- JSON ---
json_str = '{"name": "Alice", "age": 30}'
data = json.loads(json_str)
print(data["name"])  # Alice

# Serialize
output = json.dumps(data, indent=2)

# --- XML ---
xml_str = '<user><name>Alice</name><age>30</age></user>'
root = ET.fromstring(xml_str)
print(root.find('name').text)  # Alice

# --- XML with xmltodict (pip install xmltodict) ---
import xmltodict
doc = xmltodict.parse(xml_str)
print(doc['user']['name'])  # Alice

Java

// --- JSON with Jackson ---
import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> data = mapper.readValue(
    "{\"name\":\"Alice\",\"age\":30}",
    Map.class
);
System.out.println(data.get("name")); // Alice

// --- XML with Jackson XML ---
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

XmlMapper xmlMapper = new XmlMapper();
Map<String, Object> xmlData = xmlMapper.readValue(
    "<user><name>Alice</name><age>30</age></user>",
    Map.class
);

// --- XML with DOM ---
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = factory.newDocumentBuilder().parse(
    new InputSource(new StringReader(xmlStr))
);
String name = doc.getElementsByTagName("name")
    .item(0).getTextContent(); // Alice

Go

package main

import (
    "encoding/json"
    "encoding/xml"
    "fmt"
)

// --- JSON ---
type User struct {
    Name string `json:"name" xml:"name"`
    Age  int    `json:"age"  xml:"age"`
}

func main() {
    // JSON
    jsonStr := []byte(`{"name":"Alice","age":30}`)
    var user User
    json.Unmarshal(jsonStr, &user)
    fmt.Println(user.Name) // Alice

    // XML
    xmlStr := []byte(`<user><name>Alice</name><age>30</age></user>`)
    var xmlUser User
    xml.Unmarshal(xmlStr, &xmlUser)
    fmt.Println(xmlUser.Name) // Alice
}

Migration: XML to JSON Conversion Patterns

Converting XML to JSON is not always straightforward because of fundamental differences. Here are the common patterns and gotchas:

Simple Elements

<!-- XML -->
<user>
  <name>Alice</name>
  <age>30</age>
  <active>true</active>
</user>

// JSON (straightforward mapping)
{
  "name": "Alice",
  "age": 30,
  "active": true
}

Attributes

<!-- XML with attributes -->
<product id="123" category="electronics">
  <name>Laptop</name>
  <price currency="USD">999.99</price>
</product>

// JSON — Convention 1: prefix with @
{
  "@id": "123",
  "@category": "electronics",
  "name": "Laptop",
  "price": {
    "@currency": "USD",
    "#text": 999.99
  }
}

// JSON — Convention 2: flatten
{
  "id": "123",
  "category": "electronics",
  "name": "Laptop",
  "price": 999.99,
  "priceCurrency": "USD"
}

Mixed Content

<!-- XML mixed content (text + elements interleaved) -->
<p>This is <b>bold</b> and <i>italic</i> text.</p>

// JSON — No clean way to represent this!
// Option 1: HTML string
{ "p": "This is <b>bold</b> and <i>italic</i> text." }

// Option 2: Array of segments (verbose)
{
  "p": [
    { "type": "text", "value": "This is " },
    { "type": "b", "value": "bold" },
    { "type": "text", "value": " and " },
    { "type": "i", "value": "italic" },
    { "type": "text", "value": " text." }
  ]
}

Repeated Elements

<!-- XML repeated elements -->
<users>
  <user>Alice</user>
  <user>Bob</user>
  <user>Charlie</user>
</users>

// JSON — Always use arrays for repeated elements
{
  "users": ["Alice", "Bob", "Charlie"]
}

// Watch out: single-element case in XML
<users>
  <user>Alice</user>
</users>
// Some converters output a string instead of array!
// BAD:  { "users": { "user": "Alice" } }
// GOOD: { "users": { "user": ["Alice"] } }
// Always force arrays for elements that can repeat.

Important: There is no single "correct" way to convert XML to JSON. Different converters use different conventions (e.g., @attr vs _attr vs $attr for attributes). Always document your conversion convention and be consistent.

Alternatives to XML and JSON

While XML and JSON dominate, several other formats address specific needs:

FormatDescription
YAMLHuman-friendly configuration format. Popular for Docker Compose, Kubernetes, CI/CD. Superset of JSON but with comments, multi-line strings, and cleaner syntax.
TOMLMinimal, unambiguous configuration format. Used by Rust (Cargo.toml), Python (pyproject.toml). Better than JSON for config, simpler than YAML.
Protocol BuffersGoogle's binary serialization format. 3–10x smaller than JSON, much faster to parse. Requires a schema (.proto file). Ideal for microservice communication.
MessagePackBinary format compatible with JSON data types. Smaller and faster than JSON. No schema required. Good for caching, inter-service communication.
Apache AvroBinary format with schema evolution support. Popular in big data (Hadoop, Kafka). Schema is sent with data, enabling rich type information.

Frequently Asked Questions

Is JSON always faster than XML?

For parsing, JSON is generally 2–4x faster than XML DOM parsing because JSON has a simpler grammar. However, XML SAX/StAX streaming parsers can process very large files more efficiently than non-streaming JSON parsers. For small payloads under 100KB, the speed difference is negligible. The real performance gain from JSON comes from smaller file sizes, which reduce network transfer time.

Can JSON replace XML completely?

No. JSON cannot represent mixed content (text interleaved with markup), does not support namespaces, lacks a native transformation language like XSLT, and has weaker schema validation compared to XSD. Many industry standards (SOAP, RSS, SVG, Office formats, healthcare HL7) are XML-based and cannot be replaced. JSON is better for data interchange; XML is better for documents.

Why do REST APIs use JSON instead of XML?

REST APIs adopted JSON because: (1) it is natively parsed by JavaScript in browsers, (2) it produces smaller payloads than XML, (3) the syntax is simpler and easier to read, (4) it maps directly to common programming data structures (objects, arrays). SOAP APIs historically used XML, but most new APIs prefer REST with JSON.

Should I use XML or JSON for configuration files?

For most projects, JSON (or YAML/TOML) is preferred for configuration files because of simplicity and tooling. However, XML is still used for complex configurations that benefit from schema validation (Maven pom.xml, Spring XML, Android manifests). If you need comments in your config, use YAML, TOML, or XML — standard JSON does not support comments.

How do I convert XML to JSON?

Use a library appropriate for your language: <code>xml2js</code> (Node.js), <code>xmltodict</code> (Python), <code>Jackson XML</code> (Java), or <code>encoding/xml</code> (Go). Be aware that XML attributes, namespaces, and mixed content have no direct JSON equivalent, so choose a convention (like using <code>@attr</code> for attributes) and document it. Our XML Formatter tool can help you inspect XML structure before conversion.

Format and validate your XML instantly with our free XML Formatter tool →

Format and validate JSON with our free JSON Formatter tool →

𝕏 Twitterin LinkedIn
この記事は役に立ちましたか?

最新情報を受け取る

毎週の開発ヒントと新ツール情報。

スパムなし。いつでも解除可能。

Try These Related Tools

<>XML FormatterXJXML to JSON Converter{ }JSON Formatter

Related Articles

JSON vs YAML vs TOML:どの設定フォーマットを使うべき?

JSON、YAML、TOML の設定フォーマットを比較。

Protocol Buffers vs JSON:gRPC vs REST

API通信におけるProtocol BuffersとJSONの比較。gRPC vs RESTのトレードオフ、シリアライゼーション性能、スキーマ進化。