首页 > 其他 > 详细

元素以dict形式携带属性

时间:2019-10-28 16:52:50      阅读:68      评论:0      收藏:0      [点我收藏+]

创建节点时,同时创建属性

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

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

元素以dict形式携带属性

原文:https://www.cnblogs.com/shiliye/p/11753226.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!