You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python修改XML中指定名称的食品价格?

问题

我正尝试使用Python修改XML文件中的值,现有一份示例XML文件,以及一段为name元素追加文本的代码。现在需要实现:给定一个包含名称的数组(比如["Strawberry Belgian Waffles", "Belgian Waffles"]),检查name元素的值是否与数组成员完全匹配,若匹配则为其对应的price值增加2美元,需修改所有符合条件的<food>节点中的价格。

示例XML

<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'

解决方案

可以通过遍历所有<food>节点,关联检查name与price的方式实现需求,具体代码如下:

import xml.etree.ElementTree as ET

# 定义需要涨价的食品名称列表
target_names = ["Strawberry Belgian Waffles", "Belgian Waffles"]

# 解析XML文件
mytree = ET.parse('t.xml')
myroot = mytree.getroot()

# 遍历每个food节点
for food in myroot.findall('food'):
    name_elem = food.find('name')
    # 去除文本前后空白,避免因空格导致匹配失败
    name_text = name_elem.text.strip()
    
    if name_text in target_names:
        price_elem = food.find('price')
        # 转换为浮点数计算新价格,保留两位小数
        original_price = float(price_elem.text)
        new_price = original_price + 2.0
        price_elem.text = f"{new_price:.2f}"

# 保存修改后的XML文件
mytree.write('updated_t.xml', encoding='utf-8', xml_declaration=True)

关键说明

  • 直接遍历<food>节点,能更方便地关联每个食品的name和price元素,避免单独遍历name后再寻找对应父节点的麻烦;
  • 使用strip()处理name文本,防止XML中不经意的空格导致匹配失效;
  • 价格计算时转成浮点数操作,最后用格式化字符串保留两位小数,保证输出格式与原XML一致;
  • 写入文件时指定编码和XML声明,确保生成的文件格式规范。

内容的提问来源于stack exchange,提问作者Learn-code

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 10:15:54