lxml[.objectify] documentElement 标签名
我正在接收一些XML格式的数据包,每个数据包都有一个特定的文档根标签。我想根据这个根标签的名字,把处理这些数据包的工作交给专门的方法来做。在使用xml.dom.minidom的时候,我是这样做的:
dom = minidom.parseString(the_data)
root = dom.documentElement
deleg = getattr(self,'elem_' + str(root.tagName))
deleg(dom)
不过,我想在代码的其他部分简化一些事情,所以想用更符合Python风格的lxml.objectify。
问题是,我不知道怎么用lxml来获取“root.tagName”,最好是严格使用lxml.objectify。有没有什么好主意?
2 个回答
0
在 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)
而且你还可以使用一种很符合Python风格的接口,比如:doc.html.head.title = u"更改HTML文档标题"
3
在 lxml 的文档和 dir() 这个内置函数的帮助下,我成功地做出了这个:
>>> 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)