【发布时间】: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 文档并最终将其作为文件写出的功能。
-
您的数组还包含
a和b;你需要检查他们在<name>中的存在吗? -
@JackFleeting A 和 B 只是数组中的示例,我只需要匹配名称
-
@MichaelButscher 这就是我想要的,并试图扩展功能以修改节点中的各种元素及其值
-
@JackFleeting 谢谢,我现在用给定 xml 中可以匹配的值更新数组