Ad

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.

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

Ad

Answer

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

Ad
source: stackoverflow.com
Ad