2 min read

XML to JSON Converter

This utility converts XML files into JSON format. It parses the XML structure using xml.etree.ElementTree and recursively transforms it into a Python dictionary, which is then serialized to JSON.

Modules Used:

  • xml.etree.ElementTree: To parse the XML file.
  • json: To write the JSON output.
  • argparse: To handle command-line arguments.

The Code

Save this as xml2json.py.

import xml.etree.ElementTree as ET
import json
import argparse
import sys

def element_to_dict(element):
    """
    Recursively converts an ElementTree Element to a dictionary.
    """
    node = {}

    # 1. Attributes
    if element.attrib:
        node.update(("@" + k, v) for k, v in element.attrib.items())

    # 2. Text Content
    if element.text and element.text.strip():
        node["#text"] = element.text.strip()

    # 3. Children
    for child in element:
        child_data = element_to_dict(child)

        # Handle multiple children with the same tag (create list)
        if child.tag in node:
            if isinstance(node[child.tag], list):
                node[child.tag].append(child_data)
            else:
                node[child.tag] = [node[child.tag], child_data]
        else:
            node[child.tag] = child_data

    # Simplification: If node only has text, return the text directly
    if len(node) == 1 and "#text" in node:
        return node["#text"]

    return node

def convert_xml_to_json(xml_file, json_file):
    try:
        # Parse XML
        tree = ET.parse(xml_file)
        root = tree.getroot()

        # Convert to dict (wrap root tag)
        data = {root.tag: element_to_dict(root)}

        # Write JSON
        with open(json_file, 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=4)

        print(f"Successfully converted '{xml_file}' to '{json_file}'")

    except ET.ParseError as e:
        print(f"Error parsing XML: {e}")
    except FileNotFoundError:
        print(f"Error: File '{xml_file}' not found.")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="XML to JSON Converter")
    parser.add_argument("input", help="Input XML file path")
    parser.add_argument("output", help="Output JSON file path")

    args = parser.parse_args()

    convert_xml_to_json(args.input, args.output)

Usage

python xml2json.py data.xml data.json

programming/python/python