为了账号安全,请及时绑定邮箱和手机立即绑定

Python两次追加XML SubElement

Python两次追加XML SubElement

莫回无 2021-05-13 14:00:54
我编写了以下代码以附加XML SubElement,但它两次附加了相同的代码:Python代码:from xml.etree import ElementTree as ETtree = ET.parse("sample.xml")root = tree.getroot()child = parent = ''NOTFOUND = 0pos = 0for 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                continueif 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中,以确保它不会循环两次(并且也没有循环)。
查看完整描述

1 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

用 ET.dump(newattr)


前任:


from xml.etree import ElementTree as ET

tree = ET.parse(filename)

root = tree.getroot()


parent = ''

NOTFOUND = False


for user in root:

    Id = user.get("id")

    if Id == '012345':

        if "attrib3" not in [attr.get('name') for attr in user]:  

            print user, "----"          

            NOTFOUND = True

            parent = user


if NOTFOUND:

    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

    ET.dump(newattr)    #Update!!!!


tree.write(filename)


查看完整回答
反对 回复 2021-05-18
  • 1 回答
  • 0 关注
  • 230 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信