XhCode Online Converter Tools

XML To JSON Converter

Enter xml here:
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Results:
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XML To JSON

Converting XML data to JSON format can be done in several ways, including using programming languages, online tools, or command-line utilities. Below are different methods for converting XML data to JSON.

1. Using Python (Automated Conversion)
Python is a versatile programming language with libraries that allow for easy conversion of XML to JSON. The xml.etree.ElementTree module helps in parsing XML data, and json is used to write the data in JSON format.

Python Script Example:
python

import xml.etree.ElementTree as ET
import json

# Parse the XML file
tree = ET.parse('data.xml')
root = tree.getroot()

# Recursive function to convert XML to a dictionary
def xml_to_dict(element):
# Create a dictionary to hold element data
result = {}

# If the element has children, recurse through them
for child in element:
child_data = xml_to_dict(child)

# If the tag already exists, append the data to a list
if child.tag in result:
if isinstance(result[child.tag], list):
result[child.tag].append(child_data)
else:
result[child.tag] = [result[child.tag], child_data]
else:
result[child.tag] = child_data

# Add element attributes as well
if element.attrib:
result.update(('@' + key, value) for key, value in element.attrib.items())

# Add the element's text (if any)
if element.text:
text = element.text.strip()
if text:
result['#text'] = text

return result

# Convert the root XML element to a dictionary
xml_dict = xml_to_dict(root)

# Convert the dictionary to JSON
json_data = json.dumps(xml_dict, indent=4)

# Save the JSON data to a file
with open('output.json', 'w') as json_file:
json_file.write(json_data)

print("XML data has been successfully converted to JSON.")
Explanation:
ET.parse(): Parses the XML file.
Recursive Function: The xml_to_dict() function is a recursive method that iterates through XML elements and converts them into a Python dictionary.
json.dumps(): Converts the dictionary into a JSON-formatted string.
Output: The JSON is saved into a file (output.json).
2. Using PHP (Server-Side)
You can use PHP to parse XML data and convert it to JSON format by utilizing PHP's built-in simplexml_load_file() to load the XML and json_encode() to convert it to JSON.

PHP Script Example:
php

<?php
// Load the XML file
$xml = simplexml_load_file('data.xml');

// Convert XML to JSON
$json = json_encode($xml, JSON_PRETTY_PRINT);

// Save the JSON data to a file
file_put_contents('output.json', $json);

echo "XML data has been successfully converted to JSON.";
?>
Explanation:
simplexml_load_file(): This PHP function loads the XML file.
json_encode(): Converts the loaded XML data to JSON format.
Output: The resulting JSON is saved to a file (output.json).
3. Using Node.js (Automated Conversion)
If you're comfortable with JavaScript, you can use Node.js and libraries like xml2js to parse the XML and convert it to JSON.

Node.js Script Example:
First, you need to install the xml2js package:
bash

npm install xml2js
Then, use the following script to convert XML to JSON:
javascript

const fs = require('fs');
const xml2js = require('xml2js');

// Read the XML file
fs.readFile('data.xml', 'utf8', (err, data) => {
if (err) {
console.error('Error reading the file:', err);
return;
}

// Parse XML to JSON
xml2js.parseString(data, { explicitArray: false }, (err, result) => {
if (err) {
console.error('Error parsing XML:', err);
return;
}

// Convert JSON object to a JSON string
const jsonString = JSON.stringify(result, null, 4);

// Write the JSON data to a file
fs.writeFile('output.json', jsonString, (err) => {
if (err) {
console.error('Error writing JSON file:', err);
} else {
console.log('XML data has been successfully converted to JSON.');
}
});
});
});
Explanation:
xml2js.parseString(): Converts the XML string to a JavaScript object.
JSON.stringify(): Converts the JavaScript object to a JSON string.
Output: The resulting JSON is written to a file (output.json).
4. Using XSLT (For XML Transformation)
You can use XSLT to transform XML into JSON by creating an XSLT stylesheet. However, this is less commonly used than the programmatic approaches and often requires a more complex setup.

XSLT Example (simplified approach):
Here's an example of how to use XSLT to transform XML to JSON, but note that this transformation is quite basic, and you'd need an XSLT processor to run it.

xml

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text" encoding="UTF-8" />

<xsl:template match="/">
<xsl:text>{</xsl:text>
<xsl:for-each select="employees/employee">
<xsl:text>&quot;</xsl:value-of select="name"/>&quot;: {</xsl:text>
<xsl:text>&quot;id&quot;: &quot;</xsl:value-of select="id"/>&quot;,</xsl:text>
<xsl:text>&quot;age&quot;: &quot;</xsl:value-of select="age"/>&quot;,</xsl:text>
<xsl:text>&quot;city&quot;: &quot;</xsl:value-of select="city"/>&quot;</xsl:text>
<xsl:text>}</xsl:text>
<xsl:if test="position()!=last()">,</xsl:if>
</xsl:for-each>
<xsl:text>}</xsl:text>
</xsl:template>
</xsl:stylesheet>
This XSLT script would transform XML into a JSON-like string (though more complex cases would require more sophisticated XSLT).

5. Using Online Tools
For a quick conversion without coding, there are various online tools that can convert XML to JSON:

XML to JSON Converter: Paste your XML data into the input box and click the "Convert" button to get the JSON output.
Free XML to JSON Tool: Upload an XML file or paste its content, and the tool will convert it into JSON.
These tools are good for simple, one-off conversions without requiring code.

6. Using Excel (Manual Conversion)
You can manually open an XML file in Excel and save it as JSON by first opening the file, parsing the XML data into rows and columns, and then using a JSON conversion tool or script.

Steps:
Open XML in Excel: Go to Data > Get Data > From File > From XML.
Save Data: Once the XML is parsed, save the data into a structured format.
Convert to JSON: Use an online tool or script (like Python) to convert the structured data from CSV or Excel to JSON.
Summary of Methods:
Python: Use Python with xml.etree.ElementTree and json to convert XML to JSON.
PHP: Use PHP with simplexml_load_file() and json_encode() to convert XML to JSON.
Node.js: Use the xml2js library in Node.js to parse and convert XML to JSON.
XSLT: Use XSLT to transform XML into JSON (requires more setup).
Online Tools: Use online converters for quick XML to JSON conversion.
Excel: Open XML in Excel and convert the data to JSON using external tools.