我正在尝试在python的xml.etree.ElementTreeElementTreeElement创建一个小的插件,该插件可以使用如下符号:

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.parseET.fromstringET.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__情况下是否可行?

相关: 如何在python中继承ElementTree.Element类?

===============>>#1 票数:1 已采纳

由于导入了Element和XMLParser的C实现,因此无法覆盖该类:

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

===============>>#2 票数:1

我遇到了类似的问题,但偶然发现了一个快速的解决方法:
我在python 3.7之前的版本中导入了xmlschema ,并且没有问题用setattr猴子ET.Element

编辑:由于这很有趣,因此我对此进行了进一步研究。 这是猴子补丁ElementTree的方法

  ask by arve0 translate from so

未解决问题?本站智能推荐: