Archivos .xml#
Ultima modificación: Mayo 14, 2022
Escritura#
[1]:
import xml.etree.ElementTree as ET
from xml.dom import minidom
config = ET.Element('config')
as_dict = ET.SubElement(config, 'as_dict')
as_dict_host = ET.SubElement(as_dict, 'host')
as_dict_host.text = 'localhost'
as_dict_port = ET.SubElement(as_dict, 'port')
as_dict_port.text = '8082'
as_list = ET.SubElement(config, 'as_list')
as_list_values = ET.SubElement(as_list, 'value', {'value': 'value 0'})
as_list_values = ET.SubElement(as_list, 'value', {'value': 'value 1'})
as_list_values = ET.SubElement(as_list, 'value', {'value': 'value 2'})
as_integer = ET.SubElement(config, 'as_integer')
as_integer.text = '100'
as_float = ET.SubElement(config, 'as_float')
as_float.text = '1.0'
with open('config.xml', 'w') as out_file:
text = ET.tostring(config)
text = minidom.parseString(text)
text = text.toprettyxml(indent=" ")
print(text, file=out_file)
[2]:
!cat config.xml
<?xml version="1.0" ?>
<config>
<as_dict>
<host>localhost</host>
<port>8082</port>
</as_dict>
<as_list>
<value value="value 0"/>
<value value="value 1"/>
<value value="value 2"/>
</as_list>
<as_integer>100</as_integer>
<as_float>1.0</as_float>
</config>
Lectura#
[3]:
tree = ET.parse('config.xml')
root = tree.getroot()
value = root.findall('as_dict')[0]
value.tag
[3]:
'as_dict'
[4]:
value[0].tag, value[0].text
[4]:
('host', 'localhost')
[5]:
value[1].tag, value[1].text
[5]:
('port', '8082')
[6]:
!rm config.xml