我的第一个问题
我正在努力清理那些没有设定价格或数量的产品的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)删除了错误的元素
因此,如果有人知道错误的内容和位置,我会非常高兴 感谢您的时间。我也批评我的问题,我做错了什么以及我能做得更好。
答案 0 :(得分:0)
问题是你在迭代它时修改树。
而不是
you can use like this.
<html>
<head>
<script type="text/javascript">
var q1="hello";
<?php
$ff ="<script>document.write(q1)</script>";
?>
</script>
</head>
<body>
<?php echo $ff; ?>
</body>
</html>
使用
for child in root:
请参阅此answer