World's simplest XML to JSON converter for web developers and programmers.
Simply paste your XML into the form below, click the "Convert" button, and voila—you'll get your JSON. It’s as easy as pressing a button! Just beware of any potential junk data that might sneak through.
As a developer, I've lost count of how many times I've battled with XML to JSON conversions. Whether you're working with legacy systems, integrating different APIs, or dealing with data interchange formats, the process of transforming XML to JSON has always been a pain point that eats into development time.
I created a web-based XML to JSON converter that addresses these challenges head-on. Let me break down the key features that make this tool a game-changer:
The converter provides a split-screen layout with:
The conversion script handles:
@attributes
key)The heart of the solution is a recursive xmlToJson()
function that elegantly handles complex XML structures:
function xmlToJson(xml) {
let obj = {};
// Handle element nodes
if (xml.nodeType === 1) {
// Capture attributes
if (xml.attributes.length > 0) {
obj['@attributes'] = {};
for (let j = 0; j < xml.attributes.length; j++) {
const attribute = xml.attributes.item(j);
obj['@attributes'][attribute.nodeName] = attribute.nodeValue;
}
}
}
// Handle text nodes
if (xml.nodeType === 3) {
obj = xml.nodeValue.trim();
}
// Recursively process child nodes
if (xml.hasChildNodes()) {
for (let i = 0; i < xml.childNodes.length; i++) {
const item = xml.childNodes.item(i);
const nodeName = item.nodeName;
// Skip empty text nodes
if (nodeName === '#text') continue;
const itemObj = xmlToJson(item);
// Handle multiple elements with same name
if (typeof(obj[nodeName]) === 'undefined') {
obj[nodeName] = itemObj;
} else {
if (typeof(obj[nodeName].push) === 'undefined') {
const old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(itemObj);
}
}
}
return obj;
}
import React, { useState } from 'react';
import { parseString } from 'xml2js';
const XmlToJsonConverter = () => {
const [xmlInput, setXmlInput] = useState('');
const [jsonOutput, setJsonOutput] = useState('');
const [error, setError] = useState(null);
const convertXmlToJson = () => {
try {
parseString(xmlInput, { explicitArray: false }, (err, result) => {
if (err) {
setError('Invalid XML format');
return;
}
setJsonOutput(JSON.stringify(result, null, 2));
setError(null);
});
} catch (conversionError) {
setError('Conversion failed');
}
};
return (
<div className="xml-converter">
<textarea
value={xmlInput}
onChange={(e) => setXmlInput(e.target.value)}
placeholder="Paste XML here"
/>
{error && <div className="error">{error}</div>}
<button onClick={convertXmlToJson}>Convert</button>
<pre>{jsonOutput}</pre>
</div>
);
};
import xml.etree.ElementTree as ET
import json
def xml_to_json(xml_string):
def parse_element(element):
result = {}
# Handle attributes
if element.attrib:
result['@attributes'] = element.attrib
# Handle text
if element.text and element.text.strip():
result['#text'] = element.text.strip()
# Handle child elements
for child in element:
child_result = parse_element(child)
# Handle multiple elements with same tag
if child.tag in result:
if not isinstance(result[child.tag], list):
result[child.tag] = [result[child.tag]]
result[child.tag].append(child_result)
else:
result[child.tag] = child_result
return result
root = ET.fromstring(xml_string)
return json.dumps(parse_element(root), indent=2)
# Example usage
xml_input = '''
<customers>
<customer id="55000">
<name>Charter Group</name>
<address>
<street>100 Main</street>
<city>Framingham</city>
</address>
</customer>
</customers>
'''
print(xml_to_json(xml_input))
from lxml import etree
import json
def xml_to_json_lxml(xml_string):
def parse_element(element):
result = {}
# Handle attributes
if element.attrib:
result['@attributes'] = dict(element.attrib)
# Handle text
if element.text and element.text.strip():
result['#text'] = element.text.strip()
# Handle child elements
children = element.getchildren()
if children:
for child in children:
child_name = child.tag
child_result = parse_element(child)
# Handle multiple elements with same tag
if child_name in result:
if not isinstance(result[child_name], list):
result[child_name] = [result[child_name]]
result[child_name].append(child_result)
else:
result[child_name] = child_result
return result
root = etree.fromstring(xml_string)
return json.dumps(parse_element(root), indent=2)
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class XmlToJsonConverter {
public static String convertXmlToJson(String xmlContent) throws Exception {
// Create JAXB context and unmarshaller
JAXBContext context = JAXBContext.newInstance(YourRootClass.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
// Parse XML to Java object
StringReader reader = new StringReader(xmlContent);
YourRootClass rootObject = (YourRootClass) unmarshaller.unmarshal(reader);
// Convert to JSON
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
return objectMapper.writeValueAsString(rootObject);
}
// Note: You'll need to create a corresponding Java class that matches your XML structure
public static class YourRootClass {
// Define fields matching your XML structure
private String name;
private List<Address> addresses;
// Getters, setters, constructors
}
}
package main
import (
"encoding/xml"
"encoding/json"
"fmt"
)
type Customer struct {
XMLName xml.Name `xml:"customer"`
ID string `xml:"id,attr"`
Name string `xml:"name"`
Address []Address `xml:"address"`
}
type Address struct {
Street string `xml:"street"`
City string `xml:"city"`
State string `xml:"state"`
Zip string `xml:"zip"`
}
func xmlToJson(xmlContent []byte) ([]byte, error) {
var customer Customer
// Unmarshal XML
err := xml.Unmarshal(xmlContent, &customer)
if err != nil {
return nil, err
}
// Marshal to JSON
jsonContent, err := json.MarshalIndent(customer, "", " ")
if err != nil {
return nil, err
}
return jsonContent, nil
}
Language | Pros | Cons | Best For |
---|---|---|---|
JavaScript/React | – Browser-native – No additional libraries required |
– Limited to browser – May struggle with complex XML |
Web applications |
Python (ElementTree) | – Part of standard library – Simple implementation |
– Limited feature set – Manual parsing required |
Small to medium XML files |
Python (lxml) | – More robust – Better performance – Advanced parsing |
– External library required | Complex XML parsing |
Java (JAXB) | – Strong typing – Enterprise-grade – Robust error handling |
– Requires class mapping – More verbose |
Enterprise applications |
Go | – Compiled language – Strong typing – Efficient |
– Requires struct definition – Less flexible |
Performance-critical apps |
As developers, we constantly seek tools that save time and reduce friction. This XML to JSON converter is my modest contribution to making data transformation easier. Feel free to customize, extend, or integrate it into your workflow.
Bonus Tip: Always validate and sanitize XML input before conversion to prevent security risks and parsing errors. And remember to validate your XML and JSON, especially when dealing with complex data structures.
Happy coding! 🚀👩💻👨💻
What do you think? Does this structure work for you?