Skip to content

Instantly share code, notes, and snippets.

@fvicente
Created March 31, 2017 19:51
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 fvicente/858193cd227520c5d5470e342b16fd44 to your computer and use it in GitHub Desktop.
Save fvicente/858193cd227520c5d5470e342b16fd44 to your computer and use it in GitHub Desktop.
When you are creating an XML with ElementTree but you want to manipulate all the values of text nodes
#!/usr/bin/python
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as et
class OverloadedElement(et.Element):
def __setattr__(self, name, value):
if name == "text":
value = value.replace(u'ú', 'u')
value = value.replace(u'ô', 'o')
value = value.replace(u'ã', 'a')
value = value.replace(u'ç', 'c')
super(et.Element, self).__setattr__(name, value)
main = OverloadedElement('main')
sub1 = et.SubElement(main, 'sub1')
sub1.text = u"Súb 1 Côntent"
sub2 = et.SubElement(main, 'sub2')
sub2.text = u"São Caçamba"
et.dump(main)

Note: Doesn't work with Python 2.6 nor cElementTree. Tested with Python 2.7

$ python etree_overload.py 
<main><sub1>Sub 1 Content</sub1><sub2>Sao Cacamba</sub2></main>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment