zoukankan      html  css  js  c++  java
  • 节点属性相关操作

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

    创建带属性节点

    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')]

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

  • 相关阅读:
    angularJS之路由
    angularJS之ng-repeat
    智能算法之Matlab实现(1)——遗传算法(1)
    如何快速处理线上故障
    测试计划怎么写
    接口测试基础
    HTTP 的一些问题
    DevOps简介
    什么是DevOps?
    HTTPS 如何保证数据传输的安全性
  • 原文地址:https://www.cnblogs.com/shiliye/p/11753226.html
Copyright © 2011-2022 走看看