0

我的代码出现错误:'AttributeError:Document instance has no attribute 'find'

我可以将 find 函数与 xml 文档一起使用吗?最终我想在 xml 文档中找到一个单词并替换它。

from xml.dom.minidom import parse

config_file = parse('/My/File/path/config.xml')

def find_word(p):
        index = p.find('Word')
        return index

print find_word(config_file)
4

2 回答 2

1

解析后,XML 文档是一个Document(DOM)对象,而不是字符串。Document对象确实没有find()方法,因为您不能只搜索和替换其中的文本。

如果您知道包含要更改的文本的元素的 ID 或标签,则可以使用getElementByIdorgetElementsByTagName然后在返回的元素的子元素中搜索该文本。否则,您可以递归遍历文档中的所有节点并在每个文本节点中搜索您希望更改的文本。

有关使用文档对象模型的更多信息,请参阅DOM 文档

于 2013-07-30T17:46:03.403 回答
0

这里的 config_file 是 xml.dom.minidom.Document 类型,而不是字符串。因此, find 将不起作用。在 minidom 文档上使用 getElementsByTagName 方法来查找所需的元素。

您应该改为执行以下操作,

>>> from xml.dom.minidom import parseString
>>> my_node = parseString('<root><wordA>word_a_value</wordA></root>');
>>> name = my_node.getElementsByTagName('wordA');
>>> print name[0].firstChild.nodeValue
word_a_value
>>>
于 2013-07-30T17:46:10.743 回答