如何使用python修改xml中的值?



我正在尝试使用python修改xml文件的值。下面是一个示例xml文件

我编写了一段代码,通过迭代将文本添加到名称中。

如果给定数组中的一组输入,如何检查值的名称例如:"比利时Waffles"再加上2美元的价格?

example: array=[Strawberry比利时华夫饼,比利时华夫饼]"比利时华夫饼";存在价格

加2$修改名称与数组成员

完全相同的元素中的price。
<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'

试试这样做:

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())

输出应该是你想要的。

最新更新