在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>
答案 0 :(得分:2)
您可以使用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中测试。