Skip to content

Instantly share code, notes, and snippets.

@nakagami
Last active March 12, 2025 05:45
Show Gist options
  • Save nakagami/9fbcb9f3d78258efaa62dead497f2e12 to your computer and use it in GitHub Desktop.
Save nakagami/9fbcb9f3d78258efaa62dead497f2e12 to your computer and use it in GitHub Desktop.
# Related to https://gist.github.com/nakagami/b822ad3fcb72645f003e639060586be9
# Retain the first element, delete the rest.
# modify attribute
# modify element
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>
'''
root = ET.fromstring(xml_data)
for i, person in enumerate(root.iter("person")):
if i == 0:
person.set("id", "100")
name = person.find("name")
name.text = 'John Doe Jr.'
age = person.find('age')
age.text = '31'
else:
root.remove(person)
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