lxml etree 的 Python 对象包装器?
给定 lxml.etree 是否可以以某种方式构造树的对象表示,以便可以以类似对象的方式访问子元素(使用“.”运算符)?
我知道 lxml 有一个名为 objectify 的库,但看起来它只能在给定原始 XML 的情况下构建,并且向树添加新元素仍然需要经历类似 etree 的节点创建。
理想情况下我想要实现的是:
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' )
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' )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想你必须分别重写 __setattribute__ 和 __getattribute__ 运算符。我想你必须子类化 etree.Element 类才能实现这一点。
但是,另一方面,这个 API 也非常不切实际,因为可能有多个具有相同标签名称的子节点。
要查找元素,您还可以使用 XPath 表达式,它与您的想法相关。 API如下:
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: