Search code examples
pythonxmlminidom

How to change the Element Name in XML using minidom + python


<CCC>
    <BBB>This is test</BBB>
</CCC>

Here I need to modify the CCC to XXX. How do I do this using minidom and Python?

Expected Output:

<XXX>
    <BBB>This is test</BBB>
</XXX>

Solution

  • You can change the node name by setting the tagName attribute Try this,

    tag_ccc = dom2.getElementsByTagName("CCC")[0]
    tag_ccc.tagName = "XXX"
    

    This should change the tag name to "XXX", below is the test code i used to confirm this using python 2.7

    from xml.dom.minidom import parse, parseString
    xml ="""<CCC><BBB>This is test</BBB></CCC>"""    
    dom = parseString(xml)
    tag_ccc = dom.getElementsByTagName("CCC")[0]
    tag_ccc.tagName = "XXX"
    print tag_ccc.toxml("utf-8")
    

    Hope this helped.