Python使用.find搜索XML(属性错误)
我的代码出现错误:“AttributeError:文档实例没有“find”属性 我可以对xml文档使用find函数吗?最后,我想找到一个单词,并在xml文档中替换它Python使用.find搜索XML(属性错误),python,xml,Python,Xml,我的代码出现错误:“AttributeError:文档实例没有“find”属性 我可以对xml文档使用find函数吗?最后,我想找到一个单词,并在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_w
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)
解析后,XML文档是
文档
(DOM)对象,而不是字符串Document
对象确实没有find()
方法,因为您不能只搜索和替换其中的文本
如果知道包含要更改的文本的元素的ID或标记,可以使用getElementById
或getElementsByTagName
然后在返回元素的子元素中搜索文本。否则,您可以递归遍历文档中的所有节点,并在每个文本节点中搜索要更改的文本
有关使用文档对象模型的详细信息,请参阅。此处的配置文件的类型为xml.dom.minidom.Document,而不是string。因此,查找将不起作用。在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
>>>
>>从xml.dom.minidom导入解析字符串
>>>my_node=parseString('word_a_value');
>>>name=my_node.getElementsByTagName('wordA');
>>>打印名称[0]。firstChild.nodeValue
单词a值
>>>