How to modify values in xml using python?


I am trying to modify the values of xml files using python.
Here is a sample xml file

I wrote a code for adding the text to the name with iteration.

If given a set of inputs in an array, how can we check the values name
example:"Belgian Waffles" and add 2$ more price to it ?

example : array=[Strawberry Belgian Waffles,Belgian Waffles]
If "Belgian Waffles" is present
add 2$ to price

modify the price in the elements where the name is exactly the same as the array member

        <name itemid="11">Belgian Waffles</name>
        <description>Two of our famous Belgian Waffles
with plenty of real maple syrup</description>
        <name itemid="21">Strawberry Belgian Waffles</name>
        <description>Light Belgian waffles covered
with strawberries and whipped cream</description>
        <name itemid="31">Berry-Berry Belgian Waffles</name>
        <description>Light Belgian waffles covered with
an assortment of fresh berries and whipped cream</description>
        <name itemid="41">French Toast</name>
        <description>Thick slices made from our
homemade sourdough bread</description>
import xml.etree.ElementTree as ET

mytree = ET.parse('t.xml')
myroot = mytree.getroot()



for names in myroot.iter('name'):
    names.text = names.text + ' <br> testdrive'
Asked By: Learn-code



Try it this way:

waffles = ["Strawberry Belgian Waffles", "Belgian Waffles"]

for food in myroot.findall('.//food'):
    item = food.find('./name').text
    if item in waffles:
        cur_price = food.find('.//price').text

        #next one is a little tricky - the price is a string on which you need
        #to perform a math function; so it needs to be converted to float and 
        #then back to string for insertion in the element

        food.find('.//price').text= str(float(cur_price)+2)

Output should be what you’re looking gor.

Answered By: Jack Fleeting
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.