[英]Error while modifying xml file with python using element tree?
这是 xml 文件类型,我正在尝试修改元素
假设 xml 文件名为“t.xml”
我使用元素树通过 python 修改它并获取我可以使用逻辑修改的元素并批量执行
我尝试打印名称以检查其是否正常工作,但即使正在执行 python 文件,我也无法获得任何 output。
如何在自定义中修改 c3 值???
<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>
<city></city>
<state></state>
<custom>
<c1>11</c1>
<c2>ee</c2>
<c3>king</c3>
</custom>
</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>
<city></city>
<state></state>
<custom>
<c1>12</c1>
<c2>ff</c2>
<c3>bye</c3>
</custom>
</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>
<city></city>
<state></state>
<custom>
<c1>13</c1>
<c2>gg</c2>
<c3>getin</c3>
</custom>
</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>
<city></city>
<state></state>
<custom>
<c1>15</c1>
<c2>hh</c2>
<c3>python</c3>
</custom>
</food>
</breakfast_menu>
import xml.etree.ElementTree as ET
mytree = ET.parse('t.xml')
myroot = mytree.getroot()
for x in myroot.findall('food'):
item = x.find('name').text
print(item)
请指导
谢谢
要打印“名称”(如您的代码想要做的那样):
from xml.etree import ElementTree as ET
elem_tree = ET.parse('t.xml')
root = elem_tree.getroot()
for food in root.findall('food'):
for name in food.findall('name'):
print("name: {}, id: {}".format(name.text, name.get('itemid')))
修改“c3”:
from xml.etree import ElementTree as ET
elem_tree = ET.parse('t.xml')
root = elem_tree.getroot()
for food in root.findall('food'):
for custom in food.findall('custom'):
for c3 in custom.findall('c3'):
c3.text = 'Modified value'
print(ET.tostring(root, encoding='unicode', method='xml')) # Print to console
# elem_tree.write('t_modified.xml') # Write to file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.