# Continue to write the Python script to convert the JSON to XML using the 'name' as the file name for each XML.
import os
import xml.etree.ElementTree as ET
import json
# 用你的 JSON 文件路径替换这里的路径
with open(r'C:\Users\lenovo\Desktop\anno_train.json', 'r', encoding='utf-8') as file:
data = json.load(file)
def create_xml_element_from_dict(parent, dict_obj):
""" Recursively create XML elements from dictionary keys and assign their values """
for key, value in dict_obj.items():
if isinstance(value, dict): # If value is a dict, make a subelement and recurse
sub_element = ET.SubElement(parent, key)
create_xml_element_from_dict(sub_element, value)
elif isinstance(value, list): # If value is a list, create a subelement for each item
for item in value:
sub_element = ET.SubElement(parent, key)
sub_element.text = str(item)
else: # If value is neither dict nor list, just assign the value
sub_element = ET.SubElement(parent, key)
sub_element.text = str(value)
def json_to_xml_file(json_obj, directory):
""" Takes a JSON object and creates an XML file with a specific name """
# Create a root element
root = ET.Element('annotation')
# Exclude 'name' from the XML structure; use it only for the file name
json_obj_except_name = {k: v for k, v in json_obj.items() if k != 'name'}
# Create XML elements from dictionary
create_xml_element_from_dict(root, json_obj_except_name)
# Convert to a string of XML
xml_str = ET.tostring(root, encoding='unicode')
# Define the file path
file_name = f"{json_obj['name'].split('.')[0]}.xml" # Using name value without file extension
file_path = os.path.join(directory, file_name)
# Save to file
with open(file_path, 'w') as file:
file.write(xml_str)
# Now let's create the XML files using the JSON data
# xml_directory修改为存储xml文件路径,xml_files_with_names不要修改!!!
xml_directory = 'E:/Py/yolo/data_xml/xml_files_with_names' # Define the directory to save XML files
os.makedirs(xml_directory, exist_ok=True) # Create the directory if it does not exist
# Generate XML files
for json_obj in data:
json_to_xml_file(json_obj, xml_directory)
# Check if the files were created properly
created_files = os.listdir(xml_directory)
# created_files[:5] # Display the first 5 file names as a check