我的第一个问题
我试图清理eshop数据库转储的产品,要么没有价格或数量设置。所以我只准备出售产品。我正试图通过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)删除不正确的元素
因此,如果有人知道bug在哪里和什么地方,我会非常高兴的感谢您的时间。我也愿意批评我的问题,我做错了什么,我可以做得更好。
发布于 2016-07-07 08:18:43
https://stackoverflow.com/questions/38240273
复制相似问题