Skip to content

Instantly share code, notes, and snippets.

@nakagami
Last active March 13, 2024 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nakagami/b822ad3fcb72645f003e639060586be9 to your computer and use it in GitHub Desktop.
Save nakagami/b822ad3fcb72645f003e639060586be9 to your computer and use it in GitHub Desktop.
XML manipuration example
import xml.etree.ElementTree as ET
xml_data = '''<?xml version="1.0" encoding="utf-8"?>
<root>
<person id="1">
<name>John Doe</name>
<age>30</age>
<city>Tokyo</city>
</person>
<person id="2">
<name>Jane Smith</name>
<age>25</age>
<city>New York</city>
</person>
</root>
'''
print(xml_data)
root = ET.fromstring(xml_data)
# add and update
for person in root.findall('.//person[@id="1"]'):
person.set("id", "3") # update attribute
name = person.find('name')
print(f"old_name={name.text}")
name.text = 'John Doe Jr.' # update text
name.set("#test_attr", "test") # new attribute
age = person.find('age')
print(f"old_age={age.text}")
age.text = '31'
new_element = ET.SubElement(person, "dc:description") # populate tag
new_element.text = "Ikebukuro"
# search again
for person in root.findall('.//person[@id="3"]'):
name = person.find('name')
print(f"new_name={name.text}")
print(f"new_age={age.text}")
print()
edited_xml = ET.tostring(root, encoding='utf-8', method='xml', xml_declaration=True).decode('utf-8')
print(edited_xml)
# remove
for person in root.findall('.//person[@id="3"]'):
name = person.find('name')
attr1 = name.get("#test_attr") # get attrib
attr2 = name.attrib.pop("#test_attr", None) # get and remove attrib
assert attr1 == attr2
age = person.find('age')
person.remove(age) # remove tag
print()
edited_xml = ET.tostring(root, encoding='utf-8', method='xml', xml_declaration=True).decode('utf-8')
print(edited_xml)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment