使用 etree 删除元素

Removing elements with etree

Relationship 下,我只想保留具有 TO_FDN="FtpServer=,并删除所有其他人。我如何在 python 2.6 中用 etree 做到这一点?

 <Relationship>
    <AssociableNode AssociationType="ManagedElement_to_ftpBackupStore" TO_FDN="FtpServer=BACKUP,FtpService=BACKUP" />
    <AssociableNode AssociationType="ManagedElement_to_ftpLicenseKeyStore" TO_FDN="FtpServer=LICENSE,FtpService=LICENSE" />
    <AssociableNode AssociationType="ManagedElement_to_ftpSwStore" TO_FDN="FtpServer=SOFTWARE,FtpService=SOFTWARE_RBS" />
    <AssociableNode AssociationType="Group_to_MeContext" TO_FDN="Group=CR94180381" />
    <AssociableNode AssociationType="MgmtAssociation" TO_FDN="ManagementNode=ONRM" />
    <AssociableNode AssociationType="StnFunction_to_NodeBFunction" FROM_FDN="SubNetwork=$parent,MeContext=$VAR_N1E_NM,ManagedElement=1,NodeBFunction=1" TO_FDN="SubNetwork=IPRAN,ManagedElement=TCU_MTUC_VODO_B_BRIJEG,StnFunction=STN_ManagedFunction" />
    <AssociableNode AssociationType="Group_to_MeContext" TO_FDN="SubNetwork=$parent,Group=RBS" />
 </Relationship>

您可以使用 Element.remove:

XMLtext = '''
<root>
 <Relationship>
    <AssociableNode AssociationType="ManagedElement_to_ftpBackupStore" TO_FDN="FtpServer=BACKUP,FtpService=BACKUP" />
    <AssociableNode AssociationType="ManagedElement_to_ftpLicenseKeyStore" TO_FDN="FtpServer=LICENSE,FtpService=LICENSE" />
    <AssociableNode AssociationType="ManagedElement_to_ftpSwStore" TO_FDN="FtpServer=SOFTWARE,FtpService=SOFTWARE_RBS" />
    <AssociableNode AssociationType="Group_to_MeContext" TO_FDN="Group=CR94180381" />
    <AssociableNode AssociationType="MgmtAssociation" TO_FDN="ManagementNode=ONRM" />
    <AssociableNode AssociationType="StnFunction_to_NodeBFunction" FROM_FDN="SubNetwork=$parent,MeContext=$VAR_N1E_NM,ManagedElement=1,NodeBFunction=1" TO_FDN="SubNetwork=IPRAN,ManagedElement=TCU_MTUC_VODO_B_BRIJEG,StnFunction=STN_ManagedFunction" />
    <AssociableNode AssociationType="Group_to_MeContext" TO_FDN="SubNetwork=$parent,Group=RBS" />
 </Relationship>
</root>
'''

from xml.etree import ElementTree as ET
root = ET.XML(XMLtext)

for relationship in root.findall('.//Relationship'):
    for associable in relationship.findall('AssociableNode'):
        if not associable.get('TO_FDN', '').startswith("FtpServer="):
            relationship.remove(associable)

print ET.tostring(root)

注意:仅在 Python2.7.

中测试