点击此处浏览总目录

节点属性相关操作

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

 

创建带属性节点

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

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

posted @ 2019-10-28 16:32  立业的博客  阅读(201)  评论(0编辑  收藏  举报