1
- def test ():
2
- print ("hi" )
1
+ import json
2
+ import xml .etree .ElementTree as ET
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
+ # Input JSON file
34
+ input_json_file = "test-input.json"
35
+ # Output XML file
36
+ output_xml_file = "test-output.xml"
37
+
38
+ try :
39
+ # Load JSON data from a file
40
+ with open (input_json_file , "r" ) as json_file :
41
+ json_data = json .load (json_file )
42
+
43
+ # Convert JSON to XML
44
+ xml_data = json_to_xml (json_data )
45
+
46
+ # Add XML header
47
+ xml_data_with_header = f"<?xml version=\" 1.0\" encoding=\" UTF-8\" ?>\n { xml_data } "
48
+
49
+ # Save to XML file
50
+ save_xml_file (xml_data_with_header , output_xml_file )
51
+ print (f"XML file saved successfully to { output_xml_file } " )
52
+
53
+ except Exception as e :
54
+ print (f"Error: { e } " )
55
+
56
+
3
57
if __name__ == "__main__" :
4
- test ()
58
+ main ()
0 commit comments