|
| 1 | +import json |
| 2 | +import os |
| 3 | +import xml.etree.ElementTree as ET |
| 4 | + |
| 5 | + |
| 6 | +#JSON file |
| 7 | +data = { |
| 8 | + |
| 9 | + "nombre":"raul", |
| 10 | + "edad": "32", |
| 11 | + "fecha_nacimiento": "11/09/1991", |
| 12 | + "lenguajes": ["Python","Javascript","Abap"] |
| 13 | +} |
| 14 | + |
| 15 | +#Parse dictionay to JSON |
| 16 | +data_json = json.dumps(data) |
| 17 | + |
| 18 | +path = os.path.join(os.path.dirname(__file__),"fichero.json") |
| 19 | + |
| 20 | +with open(path,"w") as file: |
| 21 | + file.write(data_json) |
| 22 | + |
| 23 | +data_file = "" |
| 24 | +with open(path,"r") as file: |
| 25 | + data_file = file.read() |
| 26 | + |
| 27 | +#Parse document into dictionay |
| 28 | +decoder_info = json.JSONDecoder().decode(s=data_file) |
| 29 | + |
| 30 | +#Remove file |
| 31 | +os.remove(path) |
| 32 | + |
| 33 | + |
| 34 | +#XML |
| 35 | +path_xml = "" |
| 36 | + |
| 37 | +path_xml = os.path.join(os.path.dirname(__file__),"fichero.xml") |
| 38 | + |
| 39 | +#Create xml |
| 40 | + |
| 41 | +root = ET.Element("data") |
| 42 | +name = ET.SubElement(root,"name") |
| 43 | +name.text = "Raul" |
| 44 | +age = ET.SubElement(root,"age") |
| 45 | +age.text = "33" |
| 46 | +birthDate = ET.SubElement(root,"birth_date") |
| 47 | +birthDate.text = "11/0971991" |
| 48 | +languages = ET.SubElement(root,"languages") |
| 49 | +item1 = ET.SubElement(languages,"item") |
| 50 | +python = ET.SubElement(item1,"language") |
| 51 | +python.text = "python" |
| 52 | +item2 = ET.SubElement(languages,"item") |
| 53 | +abap = ET.SubElement(item2,"language") |
| 54 | +abap.text = "abap" |
| 55 | +item3 = ET.SubElement(languages,"item") |
| 56 | +javascript = ET.SubElement(item3,"language") |
| 57 | +javascript.text = "javascript" |
| 58 | + |
| 59 | +#Build xml tree |
| 60 | +tree = ET.ElementTree(root) |
| 61 | +#Write xml tree to file |
| 62 | +tree.write(path_xml,encoding="UTF-8") |
| 63 | + |
| 64 | +#Read XML |
| 65 | + |
| 66 | +tree = ET.parse(source=path_xml) |
| 67 | + |
| 68 | +root = tree.getroot() |
| 69 | + |
| 70 | +#Iterate over elements |
| 71 | +for element in root: |
| 72 | + print(f'{element.tag}: {element.text}') |
| 73 | + |
| 74 | +os.remove(path_xml) |
| 75 | + |
0 commit comments