Aravind
Aravind

Reputation: 845

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>

Upvotes: 3

Views: 1002

Answers (2)

Radan
Radan

Reputation: 1650

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.

Upvotes: 5

Laurent LAPORTE
Laurent LAPORTE

Reputation: 22952

You can change the element name by modifying the tagName of the node. For instance:

root = dom.getElementsByTagName('CCC')[0]
root.tagName = 'XXX'

You get:

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

The documentation is available here.

Upvotes: 1

Related Questions