簡體   English   中英

使用元素樹用 python 修改 xml 文件時出錯?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM