1
+ import os
2
+ import xml .etree .ElementTree as ET
3
+ import json
4
+
5
+ # ---- xml ----
6
+ root = ET .Element ("root" ) # Crear el nodo raíz
7
+
8
+ nombre = ET .SubElement (root , "nombre" ) # Crear un nodo hijo
9
+ nombre .text = "Hyromy" # Asignar un valor al nodo hijo
10
+
11
+ edad = ET .SubElement (root , "edad" )
12
+ edad .text = "20"
13
+
14
+ fecha_nacimiento = ET .SubElement (root , "fecha_nacimiento" )
15
+ fecha_nacimiento .text = "2004-12-04"
16
+
17
+ lenguajes = ET .SubElement (root , "lenguajes" )
18
+ lenguajes_list = ["Java" , "PHP" , "C#" , "Python" , "JavaScript" ]
19
+ for lenguaje in lenguajes_list :
20
+ lenguaje_node = ET .SubElement (lenguajes , "item" )
21
+ lenguaje_node .text = lenguaje
22
+
23
+ xml_file_name = __file__ [:- 3 ] + ".xml"
24
+ tree = ET .ElementTree (root )
25
+ tree .write (xml_file_name , encoding = "utf-8" , xml_declaration = True )
26
+ del tree
27
+ del root
28
+
29
+ tree = ET .parse (xml_file_name )
30
+ root = tree .getroot ()
31
+
32
+ def read_xml (root : ET .Element , ident = 0 ):
33
+ for child in root :
34
+ if not len (child ):
35
+ print (f"{ '\t ' * ident } <{ child .tag } >{ child .text } </{ child .tag } >" )
36
+ else :
37
+ print (f"{ '\t ' * ident } <{ child .tag } >" )
38
+ read_xml (child , ident + 1 )
39
+ print (f"{ '\t ' * ident } </{ child .tag } >" )
40
+
41
+ read_xml (root )
42
+ os .remove (xml_file_name )
43
+
44
+ print ("\n \n " )
45
+
46
+ # ---- json ----
47
+ json_data = {
48
+ "nombre" : "Hyromy" ,
49
+ "edad" : 20 ,
50
+ "fecha_nacimiento" : "2004-12-04" ,
51
+ "lenguajes" : [
52
+ "Java" ,
53
+ "PHP" ,
54
+ "C#" ,
55
+ "Python" ,
56
+ "JavaScript"
57
+ ],
58
+ }
59
+
60
+ json_file_name = __file__ [:- 3 ] + ".json"
61
+
62
+ with open (json_file_name , "w" , encoding = "utf-8" ) as f :
63
+ json .dump (json_data , f , indent = 4 )
64
+ del json_data
65
+
66
+ with open (json_file_name , "r" , encoding = "utf-8" ) as f :
67
+ json_data = json .load (f )
68
+ print (json_data )
69
+
70
+ os .remove (json_file_name )
0 commit comments