节点是以字典的形式携带属性的
创建带属性节点
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操作XML节点的属性,包括创建带属性的节点、获取和设置属性值、获取所有属性并排序输出等。文章通过具体示例展示了如何进行这些操作。

被折叠的 条评论
为什么被折叠?



