21.12.2022 Views

python_para_desenvolvedores_2ed

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

XML 163

root = Element('Canino')

lobo = Element('Lobo')

raposa = Element('Raposa')

coiote = Element('Coiote')

cachorro = Element('Cachorro', nome='Bandit',

raca='Labrador', cor='Branco')

root.append(lobo)

root.append(raposa)

lobo.append(coiote)

lobo.append(cachorro)

ElementTree(root).write('caninos.xml')

Arquivo XML de saída:

<Canino>

<Lobo>

<Coiote />

<Cachorro cor="Branco" nome="Bandit" raca="Labrador" />

</Lobo>

<Raposa />

</Canino>

Exemplo de leitura do arquivo XML:

from xml.etree.ElementTree import ElementTree

tree = ElementTree(file='caninos.xml')

root = tree.getroot()

# Lista os elementos abaixo do root

print root.getchildren()

# Encontra o lobo

lobo = root.find('Lobo')

# Encontra o cachorro

cachorro = lobo.find('Cachorro')

print cachorro.tag, cachorro.attrib

# Remove a raposa

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!