1

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.

<aaa>
  <bbb>
    <name>Tom</name><number>1111</number>
    <name>Tom</name><number>2222</number>
    <name>John</name><number>3333</number>
  </bbb>
  <ccc>
    <name>None</name><number>7777</number>
    <name>Mary</name><number>8888</number>
  </ccc>
</aaa>

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.

0

1 Answer 1

1

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"

https://docs.python.org/3.5/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.findall

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

2 Comments

It can reach my requirement! Thanks for your help!
@dnisqa2delta don't forget you can accept and upvote useful answers

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.