gpt4 book ai didi

python - 继承或模拟 pythons etree.ElementTree.Element 可能吗?

转载 作者:行者123 更新时间:2023-12-01 04:42:28 25 4
gpt4 key购买 nike

我正在尝试为 ElementTree 创建一个小插件和Element在Python的xml.etree.ElementTree这将允许这样的符号:

root = ET.fromstring('<root><a><b attr1="2"/></a></root>')
element1 = root.a
element2 = root.a.b
attr = root.a.b.attr

我已经尝试过这个:

import xml.etree.ElementTree as _ET

def __getattr__(self, key):
return self.find('./' + key)

class ElementTree(_ET.ElementTree):
__getattr__ = __getattr__


class Element(_ET.Element):
__getattr__ = __getattr__

但这不起作用,因为 ET.parse , ET.fromstring , ET.ElementTree.find等将始终返回内部 ElementElementTree对象。

Monkeypatching 类也不起作用:

>>> xml.etree.ElementTree.Element.__getattr__ = lambda x: x
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-bacb0a64c2e5> in <module>()
----> 1 xml.etree.ElementTree.Element.__getattr__ = lambda x: x

TypeError: can't set attributes of built-in/extension type 'xml.etree.ElementTree.Element'

如果不复制 python etree 模块然后添加 __getattr__ 是否可行? ?

相关:How to inherit ElementTree.Element class in python?

最佳答案

由于import of the Element and XMLParser's C implementation,无法覆盖该类:

# Import the C accelerators
try:
# Element is going to be shadowed by the C implementation. We need to keep
# the Python version of it accessible for some "creative" by external code
# (see tests)
_Element_Py = Element

# Element, SubElement, ParseError, TreeBuilder, XMLParser
from _elementtree import *
except ImportError:
pass

模块_elementtree位于 Modules/_elementtree.c .

解决方案是复制 python etree 模块,并将导入更改为:

_Element_Py = Element

我做了一个简单的实现:https://github.com/arve0/objectifiedetree

像这样使用:

from objectifiedetree import *

tree = ET.parse('/path/to/file.xml')
# dot notation :-)
el = tree.xpath.to.your.element

# use normal etree attributes
print(el.attrib)

# access name crashes
attrib_el = el.find('./attrib')

关于python - 继承或模拟 pythons etree.ElementTree.Element 可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30278551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com