我编写了以下代码以附加XML SubElement,但它两次附加了相同的代码:
Python代码:
from xml.etree import ElementTree as ET
tree = ET.parse("sample.xml")
root = tree.getroot()
child = parent = ''
NOTFOUND = 0
pos = 0
for user in root:
Id = user.get("id")
if Id == '012345':
for attr in user:
attr_name = attr.get('name')
pos = len(user)
if attr_name != "attrib3" and NOTFOUND != 1:
print "#1: ", user.get('id'), attr.get('name')
NOTFOUND = NOTFOUND + 1
parent = user
child = attr
continue
if NOTFOUND == 1:
newattr = ET.SubElement(parent,'res',attrib={'name':'attrib3'})
newattr_first_seem = ET.SubElement(newattr, 'first_seem', attrib={'date':'2018-08-01', 'status':'GRANTED'})
print "#2: ", newattr.attrib
parent.append(newattr)
tree.write('sample.xml')
所需的输出:
<stop>
<user id="012345">
<res name="attrib1">
<first_seem date="2018-07-31" status="REQUESTED" />
<last_seem date="2018-07-31" status="INPROCESS" />
</res>
<res name="attrib2">
<first_seem date="2018-07-31" status="REQUESTED" />
<last_seem date="2018-07-31" status="COMPLETED" />
</res>
**<res name="attrib3">
<first_seem date="2018-08-01" status="GRANTED" />
</res>**
</user>
<user id="123456">
<res name="attrib1">
<first_seem date="2018-07-31" status="REQUESTED" />
<last_seem date="2018-07-31" status="REQUESTED" />
</res>
</user>
</stop>
有人可以帮我弄清楚为什么新的SubElement被记录两次吗?我将打印和数学控件放入if中,以确保它不会循环两次(并且也没有循环)。
慕村225694
相关分类