Python 3.8.2
xml.etree.ElementTree --- ElementTree XML API
From file
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
From a string
root = ET.fromstring(country_data_as_string)
Search only * direct child elements * of the current element by tag
#List is returned
list = root.findall('country'):
Search only the first element found by tag
elem = root.find('country'):
Search by XPath expression
root.findall("./country/neighbor")
Access content
rank = country.find('rank').text
Access attributes
#Either
country.get('name')
country.attrib['name']
elem = ET.SubElement(root,'country')
elem = ET.SubElement(root,'country', attrib={'name':'Liechtenstein'})
>>> for country in root.findall('country'):
... # using root.findall() to avoid removal during traversal
... rank = int(country.find('rank').text)
... if rank > 50:
... root.remove(country)
...
Output to sys.stdout
ET.dump(root)
Output to file
tree = ET.ElementTree(root)
tree.write('filename', encoding="utf-8", xml_declaration=True)
Output to file with line breaks
import xml.dom.minidom as md
document = md.parseString(ET.tostring(root, 'utf-8'))
with open(fname,'w') as f:
document.writexml(f, encoding='utf-8', newl='\n', indent='', addindent=' ')
Recommended Posts