使用Python查找替换元素

时间:2013-08-12 14:43:21

标签: python xml dom

我正在尝试搜索标记并替换某些XML代码中的元素。这是我的尝试:

from xml.dom import minidom

dom = minidom.parse('../../../lib/config/folder/config.xml')

for tag_type in dom.getElementsByTagName('tag_type'):
    tag_type.childNodes = [dom.createTextNode("Replacement Word")]

print tag_type

我正在运行Python 2.4,因此Element树不是一个选项。目前,我得到了回复:

<DOM Element: tag_type at 0x1c28a0e0>

不确定为什么不打印而不替换。

1 个答案:

答案 0 :(得分:3)

您必须使用Node API删除和添加节点:

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"))

演示:

>>> 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>
相关问题