2

So I realize that the docs have the list of node types for the Node class, but from poking around, I can't seem to find a way to programmatically get a list of available nodeTypes for a given Node object (short of inspecting the class, pulling every all caps member with a name ending in 'NODE', and then sorting by value). Is there any way to do this?

4

1 回答 1

1

我希望有更好的东西,但缺少它,我创建了一个新模块:

from xml.dom import Node
from collections import OrderedDict

if not hasattr(Node, 'get_all_node_types'):

    @classmethod
    def get_all_node_types(cls, refresh=False):

        if not hasattr(cls, '_type_dict') or refresh:
            unsorted_types = {getattr(cls, name) : name for name in dir(cls) if name.endswith('_NODE')}
            cls._type_dict = OrderedDict(sorted(unsorted_types.items(), key = lambda t : t[0]))
        return cls._type_dict

    setattr(Node, 'get_all_node_types', get_all_node_types)

它很hacky,所以我不太喜欢它,但只要在程序执行期间至少导入一次,我就会得到我的新方法。

于 2012-06-21T14:13:31.513 回答