在Relationship下,我希望只保留具有TO_FDN="FtpServer=的元素,并删除所有其他元素。我如何在python2.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>发布于 2015-05-05 15:06:37
你可以用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中测试。
https://stackoverflow.com/questions/30055835
复制相似问题