-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
mouredev.py
102 lines (70 loc) · 1.93 KB
/
mouredev.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import os
import xml.etree.ElementTree as xml
import json
data = {
"name": "Brais Moure",
"age": 36,
"birth_date": "29-04-1987",
"programming_languages": ["Python", "Kotlin", "Swift"]
}
xml_file = "mouredev.xml"
json_file = "mouredev.json"
"""
Ejercicio
"""
# XML
def create_xml():
root = xml.Element("data")
for key, value in data.items():
child = xml.SubElement(root, key)
if isinstance(value, list):
for item in value:
xml.SubElement(child, "item").text = item
else:
child.text = str(value)
tree = xml.ElementTree(root)
tree.write(xml_file)
create_xml()
with open(xml_file, "r") as xml_data:
print(xml_data.read())
os.remove(xml_file)
# JSON
def create_json():
with open(json_file, "w") as json_data:
json.dump(data, json_data)
create_json()
with open(json_file, "r") as json_data:
print(json_data.read())
os.remove(json_file)
"""
Extra
"""
create_xml()
create_json()
class Data:
def __init__(self, name, age, birth_date, programming_languages) -> None:
self.name = name
self.age = age
self.birth_date = birth_date
self.programming_languages = programming_languages
with open(xml_file, "r") as xml_data:
root = xml.fromstring(xml_data.read())
name = root.find("name").text
age = root.find("age").text
birth_date = root.find("birth_date").text
programming_languages = []
for item in root.find("programming_languages"):
programming_languages.append(item.text)
xml_class = Data(name, age, birth_date, programming_languages)
print(xml_class.__dict__)
with open(json_file, "r") as json_data:
json_dict = json.load(json_data)
json_class = Data(
json_dict["name"],
json_dict["age"],
json_dict["birth_date"],
json_dict["programming_languages"]
)
print(json_class.__dict__)
os.remove(xml_file)
os.remove(json_file)