0
我的第一個問題具有特定屬性的蟒蛇
刪除XML子元素我試圖清理的,要麼沒有價格或數量設置網上商店的產品數據庫轉儲。所以我只準備銷售產品。我想通過python腳本來做到這一點。 腳本未能做到我的意圖後,我試着做測試腳本。
輸入文件的test.xml
<Result >
<StoItem Code="A" Id="1" QtyFree="2" PriceEU="124.5">
<ImgGal />
</StoItem>
<StoItem Code="B" Id="2" QtyFree="2" PriceEU="124.5">
<ImgGal />
</StoItem>
<StoItem Code="C" Id="3" PriceEU="124.5">
<ImgGal />
</StoItem>
<StoItem Code="D" Id="4" QtyFree="2" >
<ImgGal />
</StoItem>
</Result>
現在我的腳本是這樣的:
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
atb='QtyFree'
for child in root:
print('Checking element no. '+child.attrib['Id'])
if atb in child.attrib:
print('In '+child.attrib['Id']+' found '+atb)
print('deleted '+child.attrib['Id'])
else:
print('In '+child.attrib['Id']+'not found '+atb)
tree.write('output.xml')
現在輸出正確識別元件,其應被刪除:
Checking element no. 1
In 1 found QtyFree
deleted 1
Checking element no. 2
In 2 found QtyFree
deleted 2
Checking element no. 3
In 3not found QtyFree
Checking element no. 4
In 4 found QtyFree
deleted 4
但當我把腳本中的實際刪除功能:
if atb in child.attrib:
print('In '+child.attrib['Id']+' found '+atb)
root.remove(child)
print('deleted '+child.attrib['Id'])
我得到的是這樣的:
Checking element no. 1
In 1 found QtyFree
deleted 1
Checking element no. 3
In 3not found QtyFree
Checking element no. 4
In 4 found QtyFree
deleted 4
而且與Output.xml看起來是這樣的:
<Result>
<StoItem Code="B" Id="2" PriceEU="124.5" QtyFree="2">
<ImgGal />
</StoItem>
<StoItem Code="D" Id="4" QtyFree="2">
<ImgGal />
</StoItem>
</Result>
含義,它
1)刪除了正確的元素
2)沒有刪除正確的元素
3)刪除不正確元素
所以,如果有人知道什麼和在哪裏的錯誤是,我會很開心 謝謝您的時間。我也接受批評我的問題,我做錯了什麼,我可以做得更好。
謝謝你,我愛你 – Budbreaker