• 节点属性相关操作


    节点是以字典的形式携带属性的

    创建带属性节点

    root = etree.Element("root", interesting="totally")
    etree.tostring(root)  #输出:b'<root interesting="totally"/>'
    
    print(root.get("interesting")) #输出:totally
    print(root.get("hello")) #输出:none

    节点属性赋值

    root.set("hello", "Huhu")
    print(root.get("hello")) #输出:Huhu
    etree.tostring(root) #输出:b'<root interesting="totally" hello="Huhu"/>'

    获取节点所有属性并排序输出

    sorted(root.keys())  #输出:['hello', 'interesting']
    
    for name, value in sorted(root.items()):
        print('%s = %r' % (name, value))
    '''
    输出:
    hello = 'Huhu'
    interesting = 'totally'
    '''

    获取节点属性集合(字典形式)

    attributes = root.attrib
    print(attributes["interesting"])  #输出:totally
    print(attributes.get("no-such-attribute")) #输出:none
    
    attributes["hello"] = "Guten Tag"
    print(attributes["hello"]) #输出:Guten Tag
    print(root.get("hello")) #输出:Guten Tag
    
    '''
    注意attrib是一个由元素本身支持的类似dict的对象。
    这意味着对元素的任何更改都反映在attrib中,反之亦然。
    这还意味着,只要XML树的某个元素的attrib在使用,它就在内存中保持活动状态。
    要获取不依赖于xml树的属性的独立快照,请将其复制到dict中
    '''
    
    d = dict(root.attrib)
    sorted(d.items()) #[('hello', 'Guten Tag'), ('interesting', 'totally')]

     -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

  • 相关阅读:
    Python有用的内置函数divmod,id,sorted,enumerate,input,oct,eval,exec,isinstance,ord,chr,filter,vars,zip
    audio的自动播放报错解决
    高德搜索定位,获取信息
    柱状图的点击事件
    高德局部刷新标记点,bug解决
    递归
    CentOS7搭建LNMP环境
    CentOS7安装RabbitMQ
    前端项目代码加密教程
    复杂度分析
  • 原文地址:https://www.cnblogs.com/shiliye/p/11753226.html
Copyright © 2020-2023  润新知