python xml添加命名空间_Python利用命名空间解析XML文档

问题

你想解析某个XML文档,文档中使用了XML命名空间。

解决方案

考虑下面这个使用了命名空间的文档:

David Beazley

Hello World

Hello World!

如果你解析这个文档并执行普通的查询,你会发现这个并不是那么容易,因为所有步骤都变得相当的繁琐。

>>> # Some queries that work

>>> doc.findtext('author')

'David Beazley'

>>> doc.find('content')

>>> # A query involving a namespace (doesn't work)

>>> doc.find('content/html')

>>> # Works if fully qualified

>>> doc.find('content/{http://www.w3.org/1999/xhtml}html')

>>> # Doesn't work

>>> doc.findtext('content/{http://www.w3.org/1999/xhtml}html/head/title')

>>> # Fully qualified

>>> doc.findtext('content/{http://www.w3.org/1999/xhtml}html/'

... '{http://www.w3.org/1999/xhtml}head/{http://www.w3.org/1999/xhtml}title')

'Hello World'

>>>

你可以通过将命名空间处理逻辑包装为一个工具类来简化这个过程:

class XMLNamespaces:

def __init__(self, **kwargs):

self.namespaces = {}

for name, uri in kwargs.items():

self.register(name, uri)

def register(self, name, uri):

self.namespaces[name] = '{'+uri+'}'

def __call__(self, path):

return path.format_map(self.namespaces)

通过下面的方式使用这个类:

>>> ns = XMLNamespaces(html='http://www.w3.org/1999/xhtml')

>>> doc.find(ns('content/{html}html'))

>>> doc.findtext(ns('content/{html}html/{html}head/{html}title'))

'Hello World'

>>>

讨论

解析含有命名空间的XML文档会比较繁琐。 上面的 XMLNamespaces 仅仅是允许你使用缩略名代替完整的URI将其变得稍微简洁一点。

很不幸的是,在基本的 ElementTree 解析中没有任何途径获取命名空间的信息。 但是,如果你使用iterparse()函数的话就可以获取更多关于命名空间处理范围的信息。例如:

>>> from xml.etree.ElementTree import iterparse

>>> for evt, elem in iterparse('ns2.xml', ('end', 'start-ns', 'end-ns')):

... print(evt, elem)

...

end

start-ns ('', 'http://www.w3.org/1999/xhtml')

end

end

end

end

end

end-ns None

end

end

>>> elem # This is the topmost element

>>>

最后一点,如果你要处理的XML文本除了要使用到其他高级XML特性外,还要使用到命名空间, 建议你最好是使用 lxml 函数库来代替 ElementTree 。 例如,lxml 对利用DTD验证文档、更好的XPath支持和一些其他高级XML特性等都提供了更好的支持。 这一小节其实只是教你如何让XML解析稍微简单一点。

以上就是Python利用命名空间解析XML文档的详细内容,更多关于Python命名空间解析XML文档的资料请关注聚米学院其它相关文章!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值