使用Python查找替换元素 [英] Find replace Element using Python

查看:57
本文介绍了使用Python查找替换元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

print tag_type

I' m正在运行Python 2.4,因此不能选择元素树。目前,我得到的响应是:

I'm running Python 2.4 so Element tree is not an option. Currently, I'm getting a response of:

<DOM Element: tag_type at 0x1c28a0e0>

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

Not sure why it isn't printing and not replacing.

推荐答案

您将不得不使用节点API 删除并添加节点:

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

演示:

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

这篇关于使用Python查找替换元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆