Cyber Whale

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.

pythontutorialxmlDevelopment tips

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.

empire burlesque bob dylan usa columbia 10.90 1985 hide your heart bonnie tyler uk cbs records 9.90 1988 greatest hits dolly parton usa rca 9.90 1982 empire burlesque bob dylan usa columbia 10.90 1985 hide your heart bonnie tyler uk cbs records 9.90 1988 greatest hits dolly parton usa rca 9.90 1982

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’)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:

empire burlesque bob dylan usa columbia 109.0 1985 hide your heart bonnie tyler uk cbs records 99.0 1988 greatest hits dolly parton usa rca 99.0 1982 empire burlesque bob dylan usa columbia 109.0 1985 hide your heart bonnie tyler uk cbs records 99.0 1988 greatest hits dolly parton usa rca 99.0 1982

By adminpythontutorialxml

Recent Posts

Archive

Tags

#CloudTechnologies #Code #CyberWhale #GenerativeAI Analytics bi Big Data Business Business growth business intelligence Cambrian Explosion Cloud data Data Capture Data Management Data Science Data Stack Data Synchronization Data Systems Data Warehouse DBLog deeplearning4j development dev tools DoorDash ELT ETL Hacks java jobs libs machine learning parsing Production python request Retail SaaS scala Strategy tip tutorial Uber word2vec xml

AI Strategy & Consulting

Build a future-ready AI strategy with trusted guidance