0

I'm getting an error with my code: 'AttributeError:Document instance has no attribute 'find'

Can I use the find function with an xml doc? Eventually I want to find a word and replace it in the xml doc.

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)

2 Answers 2

1

After parsing, the XML document is a Document (DOM) object, not a string. Document objects indeed do not have a find() method because you can't just search and replace text in them.

If you know the ID or tag of the element that contains the text you wish to change, you could use getElementById or getElementsByTagName and then search the children of the returned elements for the text. Otherwise, you can recursively walk all the nodes in the document and search each text node for the text you wish to change.

See the DOM documentation for more information on working with the Document Object Model.

Sign up to request clarification or add additional context in comments.

Comments

0

config_file here is of type xml.dom.minidom.Document and not string. And so, find will not work. Use the getElementsByTagName method on the minidom document to find the elements that you want.

You should be doing the following instead,

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.