Home > database >  How to modify values in xml using python?
How to modify values in xml using python?

Time:11-22

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

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

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

print(myroot[0][1])

print(myroot[0].food['name'].value)

for names in myroot.iter('name'):
    names.text = names.text   ' <br> testdrive'

CodePudding user response:

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)
print(ET.tostring(myroot).decode())

Output should be what you're looking gor.

  • Related