Examples
This section provides comprehensive examples of XML to JSON conversion for various use cases and scenarios.
Basic Examples
Simple XML Structure
Input XML:
<person>
<name>John Doe</name>
<age>30</age>
<email>john@example.com</email>
</person>
Output JSON:
{
"person": {
"name": "John Doe",
"age": "30",
"email": "john@example.com"
}
}
XML with Attributes
Input XML:
<book id="123" category="fiction">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<year>1925</year>
</book>
Output JSON (with attributes):
{
"book": {
"@attributes": {
"id": "123",
"category": "fiction"
},
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"year": "1925"
}
}
Output JSON (without attributes):
{
"book": {
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"year": "1925"
}
}
Complex Examples
Nested Elements with Arrays
Input XML:
<library>
<books>
<book id="1">
<title>Book One</title>
<author>Author One</author>
</book>
<book id="2">
<title>Book Two</title>
<author>Author Two</author>
</book>
</books>
<magazines>
<magazine id="1">
<title>Tech Magazine</title>
<issue>January 2024</issue>
</magazine>
</magazines>
</library>
Output JSON:
{
"library": {
"books": {
"book": [
{
"@attributes": {
"id": "1"
},
"title": "Book One",
"author": "Author One"
},
{
"@attributes": {
"id": "2"
},
"title": "Book Two",
"author": "Author Two"
}
]
},
"magazines": {
"magazine": {
"@attributes": {
"id": "1"
},
"title": "Tech Magazine",
"issue": "January 2024"
}
}
}
}
Mixed Content (Text and Elements)
Input XML:
<description>
This is a <strong>bold</strong> statement with <em>emphasis</em> and <a href="https://example.com">a link</a>.
</description>
Output JSON:
{
"description": {
"#text": "This is a bold statement with emphasis and a link.",
"strong": "bold",
"em": "emphasis",
"a": {
"@attributes": {
"href": "https://example.com"
},
"#text": "a link"
}
}
}
Real-World Examples
API Response Conversion
Input XML (API Response):
<?xml version="1.0" encoding="UTF-8"?>
<response>
<status>success</status>
<data>
<users>
<user id="1" role="admin">
<name>Alice Johnson</name>
<email>alice@company.com</email>
<permissions>
<permission>read</permission>
<permission>write</permission>
<permission>delete</permission>
</permissions>
</user>
<user id="2" role="user">
<name>Bob Smith</name>
<email>bob@company.com</email>
<permissions>
<permission>read</permission>
</permissions>
</user>
</users>
</data>
<pagination>
<page>1</page>
<limit>10</limit>
<total>2</total>
</pagination>
</response>
Output JSON:
{
"response": {
"status": "success",
"data": {
"users": {
"user": [
{
"@attributes": {
"id": "1",
"role": "admin"
},
"name": "Alice Johnson",
"email": "alice@company.com",
"permissions": {
"permission": ["read", "write", "delete"]
}
},
{
"@attributes": {
"id": "2",
"role": "user"
},
"name": "Bob Smith",
"email": "bob@company.com",
"permissions": {
"permission": "read"
}
}
]
}
},
"pagination": {
"page": "1",
"limit": "10",
"total": "2"
}
}
}
Configuration File Conversion
Input XML (Configuration):
<configuration>
<database>
<host>localhost</host>
<port>5432</port>
<name>myapp</name>
<credentials>
<username>admin</username>
<password encrypted="true">encrypted_password</password>
</credentials>
</database>
<server>
<host>0.0.0.0</host>
<port>3000</port>
<ssl enabled="true">
<certificate>cert.pem</certificate>
<key>key.pem</key>
</ssl>
</server>
<features>
<feature name="authentication" enabled="true" />
<feature name="logging" enabled="true" />
<feature name="caching" enabled="false" />
</features>
</configuration>
Output JSON:
{
"configuration": {
"database": {
"host": "localhost",
"port": "5432",
"name": "myapp",
"credentials": {
"username": "admin",
"password": {
"@attributes": {
"encrypted": "true"
},
"#text": "encrypted_password"
}
}
},
"server": {
"host": "0.0.0.0",
"port": "3000",
"ssl": {
"@attributes": {
"enabled": "true"
},
"certificate": "cert.pem",
"key": "key.pem"
}
},
"features": {
"feature": [
{
"@attributes": {
"name": "authentication",
"enabled": "true"
}
},
{
"@attributes": {
"name": "logging",
"enabled": "true"
}
},
{
"@attributes": {
"name": "caching",
"enabled": "false"
}
}
]
}
}
}
E-commerce Product Data
Input XML:
<catalog>
<products>
<product id="P001" category="electronics">
<name>Smartphone</name>
<description>
A <strong>high-performance</strong> smartphone with <em>advanced features</em>.
</description>
<price currency="USD">699.99</price>
<specifications>
<spec name="screen">6.1 inch</spec>
<spec name="storage">128GB</spec>
<spec name="camera">12MP</spec>
</specifications>
<availability>
<stock>50</stock>
<warehouse>NYC</warehouse>
</availability>
</product>
<product id="P002" category="books">
<name>Programming Guide</name>
<description>Comprehensive guide to modern programming</description>
<price currency="USD">29.99</price>
<specifications>
<spec name="pages">400</spec>
<spec name="language">English</spec>
<spec name="format">Paperback</spec>
</specifications>
<availability>
<stock>100</stock>
<warehouse>LA</warehouse>
</availability>
</product>
</products>
</catalog>
Output JSON:
{
"catalog": {
"products": {
"product": [
{
"@attributes": {
"id": "P001",
"category": "electronics"
},
"name": "Smartphone",
"description": {
"#text": "A high-performance smartphone with advanced features.",
"strong": "high-performance",
"em": "advanced features"
},
"price": {
"@attributes": {
"currency": "USD"
},
"#text": "699.99"
},
"specifications": {
"spec": [
{
"@attributes": {
"name": "screen"
},
"#text": "6.1 inch"
},
{
"@attributes": {
"name": "storage"
},
"#text": "128GB"
},
{
"@attributes": {
"name": "camera"
},
"#text": "12MP"
}
]
},
"availability": {
"stock": "50",
"warehouse": "NYC"
}
},
{
"@attributes": {
"id": "P002",
"category": "books"
},
"name": "Programming Guide",
"description": "Comprehensive guide to modern programming",
"price": {
"@attributes": {
"currency": "USD"
},
"#text": "29.99"
},
"specifications": {
"spec": [
{
"@attributes": {
"name": "pages"
},
"#text": "400"
},
{
"@attributes": {
"name": "language"
},
"#text": "English"
},
{
"@attributes": {
"name": "format"
},
"#text": "Paperback"
}
]
},
"availability": {
"stock": "100",
"warehouse": "LA"
}
}
]
}
}
}
Edge Cases
Empty Elements
Input XML:
<root>
<empty></empty>
<self-closing />
<with-text>content</with-text>
</root>
Output JSON:
{
"root": {
"empty": "",
"self-closing": "",
"with-text": "content"
}
}
Namespace Handling
Input XML:
<root xmlns:ns1="http://example.com/ns1" xmlns:ns2="http://example.com/ns2">
<ns1:element>Value 1</ns1:element>
<ns2:element>Value 2</ns2:element>
<regular>Regular element</regular>
</root>
Output JSON:
{
"root": {
"ns1:element": "Value 1",
"ns2:element": "Value 2",
"regular": "Regular element"
}
}
CDATA Sections
Input XML:
<data>
<description>
<![CDATA[This is <strong>CDATA</strong> content with <tags>]]>
</description>
<code>
<![CDATA[
function example() {
return "Hello World";
}
]]>
</code>
</data>
Output JSON:
{
"data": {
"description": "This is <strong>CDATA</strong> content with <tags>",
"code": "\n function example() {\n return \"Hello World\";\n }\n "
}
}
JavaScript Processing Examples
Processing Converted JSON
// Example: Processing the API response JSON
const responseJson = {
response: {
status: 'success',
data: {
users: {
user: [
{
'@attributes': { id: '1', role: 'admin' },
name: 'Alice Johnson',
email: 'alice@company.com',
},
],
},
},
},
};
// Extract users
const users = responseJson.response.data.users.user;
users.forEach((user) => {
console.log(`User: ${user.name}`);
console.log(`Email: ${user.email}`);
console.log(`Role: ${user['@attributes'].role}`);
});
Working with Attributes
// Helper function to extract attributes
function getAttributes(element) {
return element['@attributes'] || {};
}
// Helper function to get text content
function getTextContent(element) {
return element['#text'] || element;
}
// Example usage
const book = {
'@attributes': { id: '123', category: 'fiction' },
title: 'The Great Gatsby',
author: 'F. Scott Fitzgerald',
};
const bookId = getAttributes(book).id;
const title = getTextContent(book.title);
console.log(`Book ${bookId}: ${title}`);
Converting Back to XML (Reverse Process)
// Simple function to convert JSON back to XML
function jsonToXml(json, rootName = 'root') {
function processElement(key, value, indent = '') {
if (typeof value === 'object' && value !== null) {
if (Array.isArray(value)) {
return value.map((item) => processElement(key, item, indent)).join('\n');
} else if (value['@attributes']) {
const attrs = Object.entries(value['@attributes'])
.map(([k, v]) => `${k}="${v}"`)
.join(' ');
const content = Object.entries(value)
.filter(([k]) => k !== '@attributes')
.map(([k, v]) => processElement(k, v, indent + ' '))
.join('\n');
return `${indent}<${key}${attrs ? ' ' + attrs : ''}>${content ? '\n' + content + '\n' + indent : ''}</${key}>`;
} else {
const content = Object.entries(value)
.map(([k, v]) => processElement(k, v, indent + ' '))
.join('\n');
return `${indent}<${key}>${content ? '\n' + content + '\n' + indent : ''}</${key}>`;
}
} else {
return `${indent}<${key}>${value}</${key}>`;
}
}
return `<?xml version="1.0" encoding="UTF-8"?>\n${processElement(rootName, json)}`;
}