XML (eXtensible Markup Language) is a popular markup language designed to store and transport data with a self-descriptive and hierarchical structure.
xml.etree.ElementTree
module.import xml.etree.ElementTree as ET
tree = ET.parse('data.xml')
root = tree.getroot()
print(root.tag)
for child in root:
print(child.tag, child.attrib)
for elem in root.findall('item'):
name = elem.find('name').text
price = elem.get('price')
print(f"Name: {name}, Price: {price}")
new_item = ET.Element('item', attrib={'price': '9.99'})
name = ET.SubElement(new_item, 'name')
name.text = 'New Product'
root.append(new_item)
tree.write('updated_data.xml')
for item in root.findall('item'):
if item.find('name').text == 'Old Product':
item.find('name').text = 'Updated Product'
tree.write('updated_data.xml')
for item in root.findall('item'):
if item.get('price') == '0':
root.remove(item)
tree.write('cleaned_data.xml')
items = root.findall(".//item[@price='9.99']")
for item in items:
print(item.find('name').text)
xml_data = """<store><item price="5.99"><name>Sample</name></item></store>"""
root = ET.fromstring(xml_data)
print(root.tag)
root = ET.Element('store')
item = ET.SubElement(root, 'item', attrib={'price': '15.99'})
name = ET.SubElement(item, 'name')
name.text = 'Brand New Item'
tree = ET.ElementTree(root)
tree.write('new_store.xml')