lxml.etree 教程3:Elements carry attributes as a dict

XML元素支持属性,你可以在Element工厂里面直接创建它们。

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

 对于其它案例,比如你想做元素查找或者访问一个真实的类字典的对象。你可以使用attrib属性

>>> 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是一个Element自己支持的类字典对象。这意味着任何对Elements的改变将反应到attrib,反之亦然。这也意味着XML树一直存在内存里面只要其中一个Elements的attrib在使用。为了得到一个独立影像的属性,而不依赖于XML树,把它拷贝到字典

>>> d = dict(root.attrib)
>>> sorted(d.items())
[('hello', 'Guten Tag'), ('interesting', 'totally')]

 

posted @ 2013-06-10 20:17  小楼  阅读(915)  评论(0编辑  收藏  举报