gpt4 book ai didi

python - 使用 etree 删除元素

转载 作者:行者123 更新时间:2023-12-01 04:43:20 24 4
gpt4 key购买 nike

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中测试。

关于python - 使用 etree 删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30055835/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com