找到某些标签并写入新的xml文件

时间:2017-08-22 07:33:27

标签: xml python-2.7 elementtree

我想找到e-list标记并将其写入新的xml文件中。 xml如下,

<lsm>
    <m-id>v1</m-id>
    <name>v1</name>
    <communication>bi</communication>
    <states>
        <s-name>stage1</s-name>
        <state>
            <s-type>defaultState</s-type>
            <s-func>
                <p-name>pkgname</p-name>
                <f-list>
                    <f-name>funcNAME</f-name>
                    <f-arg>{&amp;}</f-arg>
                </f-list>
            </s-func>
        </state>
        <lib-path>libpath</lib-path>
        <e-list>
            <e-name>noEvent</e-name>
            <event>
                <nss>INC</nss>
                <nfs>INC</nfs>
                <actions>
                    <p-name>pkgName</p-name>
                    <f-list>
                        <f-name>toF</f-name>
                        <f-arg></f-arg>
                    </f-list>
                </actions>
            </event>
        </e-list> 

这是我的代码,

import xml.etree.ElementTree as ET

utree = ET.parse(r'C:\v1.xml')
uroot = utree.getroot()

for elist in uroot.iter('e-list'):
    print elist.tag                # print 3 Tags 
    for ename in elist.iter('e-name'):
        if (ename.text == 'noEvent' or 'Event'):
            print "test"        # Print "test" 3 times as i have 3 tags
            uroot.append(elist) #Commenting this line gives proper output.
utree.write('v2.xml', xml_declaration=True, encoding='UTF-8')

这将无限,无法创建新文件。

1 个答案:

答案 0 :(得分:1)

您将e-list元素的新副本一遍又一遍地附加到原始根元素。相反,您应该创建一个新的根元素并附加到该元素。

import xml.etree.ElementTree as ET

utree = ET.parse('v1.xml')
newroot = ET.Element("lsm")

for elist in utree.iter('e-list'):
    for ename in elist.iter('e-name'):
        if (ename.text == 'noEvent' or 'Event'):
            newroot.append(elist) 

ET.ElementTree(newroot).write('v2.xml', xml_declaration=True, encoding='UTF-8')