Replacing XML tags in Python
Question: I have an XML document with an `<en-media>` tag:

    
    
    <en-media type="image/png" hash="06c5ec15535babbcd3eef471f51af870"/>
    

I am trying to change that tag to a HTML `<img>` so it would look like the
following:

    
    
    <img src="06c5ec15535babbcd3eef471f51af870"/>
    

This works as the file is named after its hash.

I have been using xml.etree.ElementTree to try to do this and I have been
looking at <http://docs.python.org/2/library/xml.etree.elementtree.html> but I
cant seem to get anything near working.

Can anyone help me with this?

Thanks


Answer: Here is how it can be done with ElementTree.

Input XML (test.xml):

    
    
    <root>
      <en-media type="image/png" hash="06c5ec15535babbcd3eef471f51af870"/>
    </root>
    

Python code:

    
    
    from xml.etree import ElementTree as ET
    
    root = ET.parse("test.xml").getroot()
    
    # Get the 'en_media' element
    en_media = root.find("en-media")
    
    # Add the 'img' element (with 'src' attribute) as a sub-element of 'root'
    img = ET.SubElement(root, "img", src=en_media.get("hash"))
    
    # Remove 'en_media'
    root.remove(en_media)
    
    print ET.tostring(root)
    

Output:

    
    
    <root>
      <img src="06c5ec15535babbcd3eef471f51af870" /></root>
    

