Last active
June 17, 2022 17:45
-
-
Save Satak/7ca29b7531543fbf13fd71a9704a8f05 to your computer and use it in GitHub Desktop.
Python xml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import xml.etree.ElementTree as ET | |
def indent(elem, level=0): | |
i = "\n" + level*" " | |
if len(elem): | |
if not elem.text or not elem.text.strip(): | |
elem.text = i + " " | |
if not elem.tail or not elem.tail.strip(): | |
elem.tail = i | |
for elem in elem: | |
indent(elem, level+1) | |
if not elem.tail or not elem.tail.strip(): | |
elem.tail = i | |
else: | |
if level and (not elem.tail or not elem.tail.strip()): | |
elem.tail = i | |
tree = ET.parse('input.xml') | |
root = tree.getroot() | |
for person in root.findall('person'): | |
full_name_el = ET.Element('fullName') | |
first_name = person.find('name').text | |
last_name = person.find('lastName').text | |
full_name = f'{first_name} {last_name}' | |
full_name_el.text = full_name | |
person.insert(0, full_name_el) | |
indent(root) | |
tree.write('output.xml', encoding='utf-8', xml_declaration=True) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version='1.0' encoding='utf-8'?> | |
<data> | |
<person> | |
<name>1ÅÅ</name> | |
<lastName>1ÄÄÖÖ</lastName> | |
</person> | |
<person> | |
<name>2BB</name> | |
<lastName>2YYYY</lastName> | |
</person> | |
</data> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version='1.0' encoding='utf-8'?> | |
<data> | |
<person> | |
<fullName>1ÅÅ 1ÄÄÖÖ</fullName> | |
<name>1ÅÅ</name> | |
<lastName>1ÄÄÖÖ</lastName> | |
</person> | |
<person> | |
<fullName>2BB 2YYYY</fullName> | |
<name>2BB</name> | |
<lastName>2YYYY</lastName> | |
</person> | |
</data> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment