开发者

python: xml.etree.ElementTree, removing "namespaces"

I like the way ElementTree parses xml, in particular the Xpath feature. I've an output in xml from an application with nested tags.

I'd like to access this tags by name without specifying the namespace, is it possible? For example:

root.findall("/molpro/job")

instead of:

root.findall("{http://www.molpro.net/schema/molpro2006}molpro/{http://www.molpro.net/schema/molpro2006}j开发者_如何学运维ob")


At least with lxml2, it's possible to reduce this overhead somewhat:

root.findall("/n:molpro/n:job",
             namespaces=dict(n="http://www.molpro.net/schema/molpro2006"))


You could write your own function to wrap the nasty looking bits for example:

def my_xpath(doc, ns, xp);
    num = xp.count('/')
    new_xp = xp.replace('/', '/{%s}')
    ns_tup = (ns,) * num
    doc.findall(new_xp % ns_tup)

namespace = 'http://www.molpro.net/schema/molpro2006'
my_xpath(root, namespace, '/molpro/job')

Not that much fun I admit but a least you will be able to read your xpath expressions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜