Python两次附加XML SubElement

时间:2018-08-03 11:10:23

标签: python xml elementtree

我编写了以下代码以附加XML SubElement,但它两次附加了相同的代码:

Python代码:

private lateinit var presenter: LauncherPresenter

override fun <T : BasePresenter<V>, V : BaseView> getPresenter(): T = presenter

所需的输出:

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中,以确保它不会循环两次(并且也没有循环)。

1 个答案:

答案 0 :(得分:1)

使用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)