How To Use Python To Find The Element And Replace The Value In The Same Name Of Element In Xml File?

- 1 answer

I'm trying to find all value of element "name" which is not "None" and replace them with a new value "Anderson". So I hope the two "Tom, "John" and "Mary" would be replaced with "Anderson", but the name "None" of number 7777 won't be changed.


I only know how to use "tree.find()" to replace one value of specific element, but I don't know how to find and replace all.

For example:

a = tree.find('aaa/bbb/name')
tree.find('aaa/bbb/name').text = 'Anderson'

Does any one can give me an example for reach the requirement? Many thanks.



The following XPath expression can retrieve the nodes your asking .//name[text()!='None'] ElementTree has very limited XPath support though and I'm not sure it supports the text() function.

An alternative would be:

for name in tree.findall(".//name"):
    if name.text == 'None': continue
    # Do stuff here
    name.text = "Anderson"