escaping characters in a xml file with python
Question: I need to escape special characters in an ugly XML file (5000 lines or so
long). Here's an example of XML I have to deal with:

    
    
    <root>
     <element>
      <name>name & surname</name>
      <mail>name@name.org</mail>
     </element>
    </root>
    

Here the problem is the character "&" in the name. How would you escape
special characters like this with a Python library? I didn't find the way to
do it with [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/).


Answer: If you don't care about invalid characters in the xml you could use XML
parser's `recover` option (see [Parsing broken XML with
lxml.etree.iterparse](http://stackoverflow.com/q/2352840/4279)):

    
    
    from lxml import etree
    
    parser = etree.XMLParser(recover=True) # recover from bad characters.
    root = etree.fromstring(broken_xml, parser=parser)
    print etree.tostring(root)
    

### Output

    
    
    <root>
    <element>
    <name>name  surname</name>
    <mail>name@name.org</mail>
    </element>
    </root>
    

