【问题标题】:How to modify values in xml using python?如何使用python修改xml中的值?
【发布时间】:2022-11-22 21:04:22
【问题描述】:

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

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

如果给定数组中的一组输入,我们如何检查值名称 示例:“比利时华夫饼”并增加 2 美元的价格?

示例:数组=[草莓比利时华夫饼,比利时华夫饼] 如果存在“比利时华夫饼” 价格加 2 美元

修改名称与数组成员完全相同的元素中的价格

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

【问题讨论】:

  • “ElementTree”提供了修改 XML 文档并最终将其作为文件写出的功能。
  • 您的数组还包含ab;你需要检查他们在&lt;name&gt; 中的存在吗?
  • @JackFleeting A 和 B 只是数组中的示例,我只需要匹配名称
  • @MichaelButscher 这就是我想要的,并试图扩展功能以修改节点中的各种元素及其值
  • @JackFleeting 谢谢,我现在用给定 xml 中可以匹配的值更新数组

标签: python xml


【解决方案1】:

试试这样:

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

输出应该是你正在寻找的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 2013-09-13
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    相关资源
    最近更新 更多