Find Replace Element Using Python
I'm trying to search a tag and replace an element in some XML code. Here is my attempt: from xml.dom import minidom dom = minidom.parse('../../../lib/config/folder/config.xml') f
Solution 1:
You'll have to use the Node API to remove and add nodes:
for tag_type in dom.getElementsByTagName('tag_type'):
while tag_type.hasChildNodes():
tag_type.removeChild(tag_type.firstChild)
tag_type.appendChild(dom.createTextNode("Replacement Word"))
Demo:
>>> from xml.dom import minidom
>>> xml = '''\
... <root>
... <tag_type>
... Foo
... Bar
... </tag_type>
... </root>
... '''
>>> dom = minidom.parseString(xml)
>>> for tag_type in dom.getElementsByTagName('tag_type'):
... while tag_type.hasChildNodes():
... tag_type.removeChild(tag_type.firstChild)
... tag_type.appendChild(dom.createTextNode("Replacement Word"))
...
<DOM Text node "'Replacemen'...">
>>> print dom.toxml()
<?xml version="1.0" ?><root>
<tag_type>Replacement Word</tag_type>
</root>
Post a Comment for "Find Replace Element Using Python"