|
| 1 | +import json |
| 2 | + |
| 3 | + |
| 4 | +def json_to_xml(json_obj, line_padding=""): |
| 5 | + """ |
| 6 | + Convert a JSON object to an XML string. |
| 7 | + """ |
| 8 | + result_list = [] |
| 9 | + |
| 10 | + if isinstance(json_obj, dict): |
| 11 | + for key, value in json_obj.items(): |
| 12 | + result_list.append(f"{line_padding}<{key}>") |
| 13 | + result_list.append(json_to_xml(value, line_padding + " ")) |
| 14 | + result_list.append(f"{line_padding}</{key}>") |
| 15 | + elif isinstance(json_obj, list): |
| 16 | + for element in json_obj: |
| 17 | + result_list.append(json_to_xml(element, line_padding)) |
| 18 | + else: |
| 19 | + result_list.append(f"{line_padding}{json_obj}") |
| 20 | + |
| 21 | + return "\n".join(result_list) |
| 22 | + |
| 23 | + |
| 24 | +def save_xml_file(xml_str, output_file): |
| 25 | + """ |
| 26 | + Save the XML string to a file. |
| 27 | + """ |
| 28 | + with open(output_file, "w") as file: |
| 29 | + file.write(xml_str) |
| 30 | + |
| 31 | + |
| 32 | +def main(): |
| 33 | + """ |
| 34 | + Main function to convert a JSON file to an XML file. |
| 35 | + """ |
| 36 | + # Input JSON file |
| 37 | + input_json_file = "test-input.json" |
| 38 | + # Output XML file |
| 39 | + output_xml_file = "test-output.xml" |
| 40 | + |
| 41 | + try: |
| 42 | + # Load JSON data from a file |
| 43 | + with open(input_json_file, "r") as json_file: |
| 44 | + json_data = json.load(json_file) |
| 45 | + |
| 46 | + # Convert JSON to XML |
| 47 | + xml_data = json_to_xml(json_data) |
| 48 | + |
| 49 | + # Add XML header |
| 50 | + xml_data_with_header = ( |
| 51 | + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xml_data |
| 52 | + ) |
| 53 | + |
| 54 | + # Save to XML file |
| 55 | + save_xml_file(xml_data_with_header, output_xml_file) |
| 56 | + print(f"XML file saved successfully to {output_xml_file}") |
| 57 | + |
| 58 | + except Exception as e: |
| 59 | + print(f"Error: {e}") |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + main() |
0 commit comments