import xml.etree.ElementTree as ET
import json
def xml_to_json(xml_string):
"""
Parse an XML string and convert it to a JSON string.
The conversion follows a common XML-to-JSON convention:
- Element tag names become dictionary keys.
- Attributes are prefixed with '@' (e.g., '@attr': 'value').
- Text content is stored under '#text'.
- Multiple elements with the same tag are converted to lists.
Args:
xml_string (str): The XML string to parse.
Returns:
str: The JSON string representation.
Raises:
ET.ParseError: If the XML is invalid.
Example:
xml = '<root attr="1"><item>hello</item><item>world</item></root>'
json_str = xml_to_json(xml)
# Output: '{"root": {"@attr": "1", "item": [{"#text": "hello"}, {"#text": "world"}]}}'
"""
def etree_to_dict(element):
"""Recursively convert ElementTree element to dict."""
result = {element.tag: {}}
# Add attributes
for key, value in element.attrib.items():
result[element.tag]['@' + key] = value
# Process children
children = list(element)
if children:
for child in children:
child_dict = etree_to_dict(child)
child_tag = list(child_dict.keys())[0]
if child_tag in result[element.tag]:
if not isinstance(result[element.tag][child_tag], list):
result[element.tag][child_tag] = [result[element.tag][child_tag]]
result[element.tag][child_tag].append(child_dict[child_tag])
else:
result[element.tag][child_tag] = child_dict[child_tag]
# Add text content
if element.text and element.text.strip():
result[element.tag]['#text'] = element.text.strip()
# Clean up empty dict for leaf nodes without text/attrs
if not result[element.tag]:
result[element.tag] = None
return result
root = ET.fromstring(xml_string)
xml_dict = etree_to_dict(root)
return json.dumps(xml_dict, indent=2)
Usage Example
xml_example = """
<root xmlns="http://example.com" attr="value">
<item id="1">Hello</item>
<item id="2">World</item>
<description>Some text with <emphasis>nested</emphasis> content.</description>
</root>
"""
json_result = xml_to_json(xml_example)
print(json_result)
Output:
{
"root": {
"@xmlns": "http://example.com",
"@attr": "value",
"item": [
{
"@id": "1",
"#text": "Hello"
},
{
"@id": "2",
"#text": "World"
}
],
"description": {
"#text": "Some text with ",
"emphasis": {
"#text": "nested"
}
}
}
}
This implementation handles attributes, text content, nested elements, repeated tags (as arrays), and basic namespaces (prefixes appear in tags). For production use, consider the xmltodict library for more advanced features like full namespace support and CDATA handling.