1
+
2
+ """ /*
3
+ * IMPORTANTE: Sólo debes subir el fichero de código como parte del ejercicio.
4
+ *
5
+ * EJERCICIO:
6
+ * Desarrolla un programa capaz de crear un archivo XML y JSON que guarde los
7
+ * siguientes datos (haciendo uso de la sintaxis correcta en cada caso):
8
+ * - Nombre
9
+ * - Edad
10
+ * - Fecha de nacimiento
11
+ * - Listado de lenguajes de programación
12
+ * Muestra el contenido de los archivos.
13
+ * Borra los archivos.
14
+ *
15
+ * DIFICULTAD EXTRA (opcional):
16
+ * Utilizando la lógica de creación de los archivos anteriores, crea un
17
+ * programa capaz de leer y transformar en una misma clase custom de tu
18
+ * lenguaje los datos almacenados en el XML y el JSON.
19
+ * Borra los archivos.
20
+ */ """
21
+
22
+ #EJERCICIO
23
+
24
+ import os
25
+
26
+ #XML
27
+
28
+ import xml .etree .ElementTree as xml
29
+
30
+ data = {
31
+ "name" : "David" ,
32
+ "age" : 26 ,
33
+ "birth_date" : "10/03/1998" ,
34
+ "languages" : ["Python" , "HTML" , "CSS" ]
35
+ }
36
+
37
+ xml_file = "davidrguez98.xml"
38
+
39
+ def save_xml ():
40
+
41
+ root = xml .Element ("data" )
42
+
43
+ for key , value in data .items ():
44
+ child = xml .SubElement (root , key )
45
+ if isinstance (value , list ):
46
+ for item in value :
47
+ xml .SubElement (child , "item" ).text = item
48
+ else :
49
+ child .text = str (value )
50
+
51
+ tree = xml .ElementTree (root )
52
+ tree .write (xml_file )
53
+
54
+ save_xml ()
55
+
56
+ with open (xml_file , "r" ) as xml_data :
57
+ print (xml_data .read ())
58
+
59
+ os .remove (xml_file )
60
+
61
+ #JSON
62
+
63
+ import json
64
+
65
+ json_file = "davidrguez98.json"
66
+
67
+ def save_json ():
68
+ with open (json_file , "w" ) as json_data :
69
+ json .dump (data , json_data )
70
+
71
+ save_json ()
72
+
73
+ with open (json_file , "r" ) as json_data :
74
+ print (json_data .read ())
75
+
76
+ os .remove (json_file )
77
+
78
+ #DIFICULTAD EXTRA
79
+
80
+ save_xml ()
81
+
82
+ class Data ():
83
+
84
+ def __init__ (self , name , age , birth_date , languages ):
85
+ self .name = name
86
+ self .age = age
87
+ self .birth_date = birth_date
88
+ self .languages = languages
89
+
90
+ with open (xml_file , "r" ) as xml_data :
91
+ root = xml .fromstring (xml_data .read ())
92
+ name = root .find ("name" ).text
93
+ age = root .find ("age" ).text
94
+ birth_date = root .find ("birth_date" ).text
95
+ languages = []
96
+ for item in root .find ("languages" ):
97
+ languages .append (item .text )
98
+
99
+ xml_class = Data (name , age , birth_date , languages )
100
+ print (xml_class .__dict__ )
101
+
102
+ os .remove (xml_file )
103
+
104
+ save_json ()
105
+
106
+ with open (json_file , "r" ) as json_data :
107
+ json_dict = json .load (json_data )
108
+ json_class = Data (json_dict ["name" ], json_dict ["age" ], json_dict ["birth_date" ], json_dict ["languages" ])
109
+
110
+ print (json_class .__dict__ )
111
+
112
+ os .remove (json_file )
0 commit comments