杰瑞科技汇

python json to xml

Of course! Converting JSON to XML in Python can be done in a few ways. I'll cover the most common and robust methods, from a simple manual approach to using powerful libraries.

python json to xml-图1
(图片来源网络,侵删)

Summary of Methods

Method Pros Cons Best For
xml.etree.ElementTree (Manual) - No external dependencies
- Full control over the output
- Verbose code
- Requires manual handling of data types (lists, dicts)
Simple, predictable JSON structures where you want fine-grained control.
dicttoxml Library - Very easy to use
- Handles complex nested data automatically
- Good customization options
- Requires pip install dicttoxml
- Can produce verbose output by default
Quick and easy conversion of complex, nested Python dictionaries (from JSON) to XML.
xmltodict Library - Extremely powerful and flexible
- Handles namespaces, attributes, etc.
- Requires pip install xmltodict
- Can be more complex to configure for simple cases
Complex conversions where you need fine-grained control over how data becomes elements vs. attributes.

Method 1: Using xml.etree.ElementTree (Manual Approach)

This method is great for learning how XML is constructed and when you don't want to add external libraries. You'll parse the JSON into a Python dictionary and then manually build the XML tree.

Steps:

  1. Parse the JSON string into a Python dictionary using json.loads().
  2. Create a root XML element.
  3. Create a recursive function to iterate through the dictionary and build the XML tree.
  4. Convert the ElementTree object to a string using tostring().

Example:

import json
import xml.etree.ElementTree as ET
# 1. Sample JSON data
json_data = """
{
    "name": "John Doe",
    "age": 30,
    "isStudent": false,
    "courses": [
        {"title": "History", "credits": 3},
        {"title": "Math", "credits": 4}
    ],
    "address": {
        "street": "123 Main St",
        "city": "Anytown"
    }
}
"""
# 2. Parse JSON into a Python dictionary
data_dict = json.loads(json_data)
# 3. Function to convert dictionary to XML
def dict_to_xml(tag, d):
    """ Helper function to convert a dictionary to an XML element. """
    elem = ET.Element(tag)
    for key, val in d.items():
        # Handle lists by creating multiple child elements with the same tag
        if isinstance(val, list):
            for item in val:
                # Recursively call for each item in the list
                child = dict_to_xml(key, item)
                elem.append(child)
        # Handle nested dictionaries
        elif isinstance(val, dict):
            child = dict_to_xml(key, val)
            elem.append(child)
        # Handle simple values
        else:
            # Create a sub-element for the key and set its text
            child = ET.SubElement(elem, key)
            child.text = str(val)
    return elem
# 4. Create the root element and build the tree
root = dict_to_xml('person', data_dict)
# 5. Convert to a pretty-printed string
# ET.tostring returns bytes, so we decode it to a string.
# The 'encoding' and 'xml_declaration' ensure the output is well-formed.
xml_string = ET.tostring(root, encoding='unicode', method='xml')
print(xml_string)

Output:

python json to xml-图2
(图片来源网络,侵删)
<person>
    <name>John Doe</name>
    <age>30</age>
    <isStudent>False</isStudent>
    <courses>
        <title>History</title>
        <credits>3</credits>
    </courses>
    <courses>
        <title>Math</title>
        <credits>4</credits>
    </courses>
    <address>
        <street>123 Main St</street>
        <city>Anytown</city>
    </address>
</person>

Method 2: Using the dicttoxml Library (Recommended for most cases)

This library is specifically designed for this task and makes the process incredibly simple. It automatically handles lists, nested dictionaries, and data types.

First, install the library:

pip install dicttoxml

Example:

import json
from dicttoxml import dicttoxml
# 1. Sample JSON data
json_data = """
{
    "name": "Jane Doe",
    "age": 28,
    "isStudent": false,
    "courses": [
        {"title": "Art", "credits": 2},
        {"title": "Science", "credits": 3}
    ],
    "address": {
        "street": "456 Oak Ave",
        "city": "Otherville"
    }
}
"""
# 2. Parse JSON into a Python dictionary
data_dict = json.loads(json_data)
# 3. Convert dictionary to XML
# The 'root' argument sets the name of the root element.
# The 'item_func' argument lets you customize how list items are named.
xml_data = dicttoxml(data_dict, root='person', item_func=lambda x: 'course')
# The output is bytes, so decode it to a string
xml_string = xml_data.decode('utf-8')
print(xml_string)

Output:

<?xml version="1.0" encoding="UTF-8" ?>
<person>
    <type>dict</type>
    <name>string</name>
    <name>Jane Doe</name>
    <age>int</age>
    <age>28</age>
    <isStudent>bool</isStudent>
    <isStudent>False</isStudent>
    <courses type="list">
        <course type="dict">
            <title type="string">Art</title>
            <credits type="int">2</credits>
        </course>
        <course type="dict">
            <title type="string">Science</title>
            <credits type="int">3</credits>
        </course>
    </courses>
    <address type="dict">
        <street type="string">456 Oak Ave</street>
        <city type="string">Otherville</city>
    </address>
</person>

Note: By default, dicttoxml adds type information. You can disable this with custom_data=False.


Method 3: Using the xmltodict Library (Advanced)

This library is more powerful and is often used for both converting to and from XML. It gives you more control over whether dictionary keys become elements or attributes.

First, install the library:

pip install xmltodict

Example: xmltodict's unparse function converts a dictionary to XML. You can use the attr_type parameter to control attribute creation.

import json
import xmltodict
# 1. Sample JSON data
json_data = """
{
    "person": {
        "name": "Peter Jones",
        "age": 45,
        "isStudent": false,
        "courses": [
            {"title": "Physics", "credits": 5}
        ],
        "address": {
            "street": "789 Pine Rd",
            "city": "Science City"
        }
    }
}
"""
# 2. Parse JSON into a Python dictionary
data_dict = json.loads(json_data)
# 3. Convert dictionary to XML
# The 'attr_type' parameter determines how to handle data types.
# 'dict' means nested dicts become sub-elements.
xml_string = xmltodict.unparse(data_dict, pretty=True, attr_type=False)
print(xml_string)

Output:

<?xml version="1.0" encoding="utf-8"?>
<person>
    <name>Peter Jones</name>
    <age>45</age>
    <isStudent>false</isStudent>
    <courses>
        <title>Physics</title>
        <credits>5</credits>
    </courses>
    <address>
        <street>789 Pine Rd</street>
        <city>Science City</city>
    </address>
</person>

Which Method Should You Choose?

  • For a quick and reliable conversion of any JSON: Use dicttoxml. It's the most straightforward and requires the least amount of code.
  • For a simple script or a learning exercise: Use the xml.etree.ElementTree manual method. It helps you understand the underlying process.
  • For complex scenarios where you need fine-grained control (e.g., forcing certain keys to be attributes, handling XML namespaces): Use xmltodict. It's the most powerful and flexible option.
分享:
扫描分享到社交APP
上一篇
下一篇