lxml[.objectify] documentElement 标签名称

发布于 2024-08-15 12:18:55 字数 397 浏览 5 评论 0原文

我正在接收 XML 格式的数据包,每个数据包都有一个特定的 documentRoot 标记,并且我想根据根标记名称委托专门的方法来处理这些数据包。这与 xml.dom.minidom 一起工作,如下所示:

dom = minidom.parseString(the_data)
root = dom.documentElement
deleg = getattr(self,'elem_' + str(root.tagName))
deleg(dom)

但是,我想通过使用更Pythonic的 lxml.objectify 来简化事情(在代码的其他部分,而不是这里)。

问题是我不知道如何使用 lxml 获取“root.tagName”,最好严格使用 lxml.objectify。有什么想法吗?

I'm receiving data packets in XML format, each with a specific documentRoot tag, and I'd like to delegate specialized methods to take care of those packets, based on the root tag name. This worked with xml.dom.minidom, something like this:

dom = minidom.parseString(the_data)
root = dom.documentElement
deleg = getattr(self,'elem_' + str(root.tagName))
deleg(dom)

However, I want to simplify the things (in other parts of the code, not here) by using the more pythonic lxml.objectify.

The problem is I don't know how to get "root.tagName" with lxml, preferably strictly lxml.objectify. Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

拧巴小姐 2024-08-22 12:18:55

lxml 文档 和 dir()built_in 的帮助下,我成功地生成了这个:

>>> from lxml import objectify
>>> import StringIO
>>> tree = objectify.parse(StringIO.StringIO('<parent><child>Billy</child><child>Bob</child></parent>'))
>>> root = tree.getroot()
>>> root.tag
'parent'
>>> [(foo.tag, foo.text) for foo in root.getchildren()]
[('child', 'Billy'), ('child', 'Bob')]
>>>

看起来你需要类似的东西

deleg = getattr(self,'elem_' + str(root.tag))
deleg(tree)

With the help of the lxml docs and the dir() built_in, I managed to produce this:

>>> from lxml import objectify
>>> import StringIO
>>> tree = objectify.parse(StringIO.StringIO('<parent><child>Billy</child><child>Bob</child></parent>'))
>>> root = tree.getroot()
>>> root.tag
'parent'
>>> [(foo.tag, foo.text) for foo in root.getchildren()]
[('child', 'Billy'), ('child', 'Bob')]
>>>

Looks like you need something like

deleg = getattr(self,'elem_' + str(root.tag))
deleg(tree)
十级心震 2024-08-22 12:18:55

FWIW 在 Amara Bindery 中,您可以执行以下操作:

from amara import bindery
doc = bindery.parse(the_data)
top_elem = doc.xml_elements.next()
deleg = getattr(self, 'elem_' + str(top_elem.xml_qname))
deleg(doc)

并且您还可以获得 Pythonic API,例如: < code>doc.html.head.title = u"更改 HTML 文档标题"

FWIW in Amara Bindery you can do something like:

from amara import bindery
doc = bindery.parse(the_data)
top_elem = doc.xml_elements.next()
deleg = getattr(self, 'elem_' + str(top_elem.xml_qname))
deleg(doc)

And you get a Pythonic API as well, e.g.: doc.html.head.title = u"Change HTML document title"

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文