使用自定义元素类在 Python 中解析 xml [英] Parsing xml in Python using a custom element class

查看:28
本文介绍了使用自定义元素类在 Python 中解析 xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Python 的 xml.etree.ElementTree 模块解析 xml 文档.但是,我希望生成的树对象中的所有元素都具有我定义的一些类方法.这建议创建我自己的 Python 元素类的子类,但是我无法告诉解析器在解析时使用我自己的元素子类,而不是内置类.

I'd like to parse an xml document using Python's xml.etree.ElementTree module. However, I want all the elements in the resulting tree object to have some class methods that I define. This suggests creating my own subclass of Python's element class, but I'm having trouble telling the parser to use my own element subclass when parsing, instead of the built in class.

例如,假设我希望树中的节点有一个名为 custommethod() 的新方法.为此,我创建了一个元素子类:

For example, let's say I want the nodes in the tree to have a new method called custommethod(). To do this, I create an element subclass:

class MyElement(xml.etree.ElementTree._Element):

    def custommethod():
        . . . 

现在,当我使用

tree = xml.etree.ElementTree.parse(source)

我希望树中的所有元素都具有 custommethod() 方法.所以,

I want all the elements in tree to have the custommethod() method. So,

tree.getroot.custommethod() 

不应该失败.

但我不知道如何告诉解析器使用我的元素类 - 这甚至可能吗?Python 文档中有一些关于将自定义解析器传递给 .parse() 的提示,但没有很多细节.

But I don't know how to tell the parser to use my element class - is this even possible? There are some hints in the Python documentation about passing a custom parser to .parse(), but not a lot of details.

推荐答案

自定义 XML 解析器是 xml.etree.ElementTree.XMLParser 的子类,定义了四个函数:

A custom XML parser is a subclass of xml.etree.ElementTree.XMLParser with four functions defined:

  1. start(self, tag, attrs) 在找到开始标记时调用.
  2. end(self, tag) 在找到结束标记时调用.
  3. data(self, data) 找到数据时调用.
  4. close(self) 在解析结束时调用.
  1. start(self, tag, attrs) Called when an opening tag is found.
  2. end(self, tag) Called when an closing tag is found.
  3. data(self, data) Called when data is found.
  4. close(self) Called at the end of the parse.

你必须管理其他一切,节点的实例是如何创建的,每个标签的深度等等.请注意,data(self, data) 方法没有标签参数.

You must manage everything else, how the node's instances are created, the depth of each tag, etc. Notice that the data(self, data) method doesn't have a tag argument.

这篇关于使用自定义元素类在 Python 中解析 xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆