Python两次追加XML SubElement

我编写了以下代码以附加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中,以确保它不会循环两次(并且也没有循环)。


莫回无
浏览 231回答 1
1回答

慕村225694

用 ET.dump(newattr)前任:from xml.etree import ElementTree as ETtree = ET.parse(filename)root = tree.getroot()parent = ''NOTFOUND = Falsefor user in root:&nbsp; &nbsp; Id = user.get("id")&nbsp; &nbsp; if Id == '012345':&nbsp; &nbsp; &nbsp; &nbsp; if "attrib3" not in [attr.get('name') for attr in user]:&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print user, "----"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; NOTFOUND = True&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; parent = userif NOTFOUND:&nbsp; &nbsp; newattr = ET.SubElement(parent,'res',attrib={'name':'attrib3'})&nbsp; &nbsp; newattr_first_seem = ET.SubElement(newattr, 'first_seem', attrib={'date':'2018-08-01', 'status':'GRANTED'})&nbsp; &nbsp; print "#2: ", newattr.attrib&nbsp; &nbsp; ET.dump(newattr)&nbsp; &nbsp; #Update!!!!tree.write(filename)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python