Book a meeting
Close

Contacts

31 August 1989 Street 76,
Chișinău, Republic of Moldova

hello@cyberwhale.tech

Update XML node in Python

Update XML node in Python

I like python because it’s minimalistic and elegant.
Let’s see how to update an XML node using ElementTree.

We use CD catalog in XML as a datasource.

<?xml version="1.0" encoding="iso-8859-1" ?>
<?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>
<catalog>
  <cd>
    <title>empire burlesque</title>
    <artist>bob dylan</artist>
    <country>usa</country>
    <company>columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
  <cd>
    <title>hide your heart</title>
    <artist>bonnie tyler</artist>
    <country>uk</country>
    <company>cbs records</company>
    <price>9.90</price>
    <year>1988</year>
  </cd>
  <cd>
    <title>greatest hits</title>
    <artist>dolly parton</artist>
    <country>usa</country>
    <company>rca</company>
    <price>9.90</price>
    <year>1982</year>
  </cd>
</catalog>

Here is the python script itself.

import xml.etree.ElementTree as ET	

#parse XML file
tree = ET.parse('catalog_.xml')

#get root
root = tree.getroot()
#iterate over each price node (which is subchild of cd node)
for price in root.iter('price'):
	#get the price of CD, multiply 10
	new_price = float(price.text) * 10
	#update the text (value) of the node
	price.text = str(new_price)
	#add 'updated' attribute to mark node updated=yes
	price.set('updated', 'yes')

#can also use the same file if you want to directly update file.
tree.write('catalog_new.xml')

And the output is the following:

<catalog>
  <cd>
    <title>empire burlesque</title>
    <artist>bob dylan</artist>
    <country>usa</country>
    <company>columbia</company>
    <price updated="yes">109.0</price>
    <year>1985</year>
  </cd>
  <cd>
    <title>hide your heart</title>
    <artist>bonnie tyler</artist>
    <country>uk</country>
    <company>cbs records</company>
    <price updated="yes">99.0</price>
    <year>1988</year>
  </cd>
  <cd>
    <title>greatest hits</title>
    <artist>dolly parton</artist>
    <country>usa</country>
    <company>rca</company>
    <price updated="yes">99.0</price>
    <year>1982</year>
  </cd>
</catalog>