简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM