Python object wrapper for lxml etree?
Given lxml.etree is it possible to somehow construct an object representation of the tree, so that sub-elements can be accessed in object-like fashion (with '.' operator)?
I know lxml has a library called objectify but it looks like it can be only constructed given raw X开发者_如何学PythonML and adding new elements to the tree still requires to go through the etree-like node creation.
Ideally what I want to achieve is:
tree = objectify( etree_root )
print tree.somenode.get( 'attrib_name' )
tree.somenode.set( 'attrib_name', 'some_val' )
Node( tree.somenode, "somechild" )
tree.somenode.somechild.set( 'attrib', 'foo' )
I guess you have to override the __setattribute__
respectively the __getattribute__
operators. I guess you have to subclass the etree.Element class to achieve this.
But, on the other hand this API would also be quite impractical, since there might be multiple child-nodes with the same tag name.
To find elements you can also use XPath expressions, which correllate to your idea. The API is as follows:
subchild = root.find('child/subchild')
精彩评论