首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用etree去除元素

用etree去除元素
EN

Stack Overflow用户
提问于 2015-05-05 14:30:03
回答 1查看 41关注 0票数 1

Relationship下,我希望只保留具有TO_FDN="FtpServer=的元素,并删除所有其他元素。我如何在python2.6中使用etree来实现它呢?

代码语言:javascript
复制
 <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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-05 15:06:37

你可以用Element.remove

代码语言:javascript
复制
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中测试。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30055835

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档