How To Use Python To Find The Element And Replace The Value In The Same Name Of Element In Xml File?
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.
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
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module