Python利用命名空间解析XML文档


Posted in Python onAugust 10, 2020

问题

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

解决方案

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

<?xml version="1.0" encoding="utf-8"?>
<top>
  <author>David Beazley</author>
  <content>
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <title>Hello World</title>
      </head>
      <body>
        <h1>Hello World!</h1>
      </body>
    </html>
  </content>
</top>

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

>>> # Some queries that work
>>> doc.findtext('author')
'David Beazley'
>>> doc.find('content')
<Element 'content' at 0x100776ec0>
>>> # 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')
<Element '{http://www.w3.org/1999/xhtml}html' at 0x1007767e0>
>>> # 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'))
<Element '{http://www.w3.org/1999/xhtml}html' at 0x1007767e0>
>>> 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 <Element 'author' at 0x10110de10>
start-ns ('', 'http://www.w3.org/1999/xhtml')
end <Element '{http://www.w3.org/1999/xhtml}title' at 0x1011131b0>
end <Element '{http://www.w3.org/1999/xhtml}head' at 0x1011130a8>
end <Element '{http://www.w3.org/1999/xhtml}h1' at 0x101113310>
end <Element '{http://www.w3.org/1999/xhtml}body' at 0x101113260>
end <Element '{http://www.w3.org/1999/xhtml}html' at 0x10110df70>
end-ns None
end <Element 'content' at 0x10110de68>
end <Element 'top' at 0x10110dd60>
>>> elem # This is the topmost element
<Element 'top' at 0x10110dd60>
>>>

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

以上就是Python利用命名空间解析XML文档的详细内容,更多关于Python命名空间解析XML文档的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
测试、预发布后用python检测网页是否有日常链接
Jun 03 Python
详解Python的Twisted框架中reactor事件管理器的用法
May 25 Python
快速入手Python字符编码
Aug 03 Python
Python基于回溯法子集树模板解决最佳作业调度问题示例
Sep 08 Python
python+selenium实现163邮箱自动登陆的方法
Dec 31 Python
python实现电脑自动关机
Jun 20 Python
在Python dataframe中出生日期转化为年龄的实现方法
Oct 20 Python
python实现合并两个排序的链表
Mar 03 Python
使用python将最新的测试报告以附件的形式发到指定邮箱
Sep 20 Python
Tensorflow卷积实现原理+手写python代码实现卷积教程
May 22 Python
Django+Celery实现定时任务的示例
Jun 23 Python
python中if和elif的区别介绍
Nov 07 Python
Python如何定义有默认参数的函数
Aug 10 #Python
如何更换python默认编辑器的背景色
Aug 10 #Python
django前端页面下拉选择框默认值设置方式
Aug 09 #Python
解决Django响应JsonResponse返回json格式数据报错问题
Aug 09 #Python
django 获取字段最大值,最新的记录操作
Aug 09 #Python
在django中查询获取数据,get, filter,all(),values()操作
Aug 09 #Python
Python 使用双重循环打印图形菱形操作
Aug 09 #Python
You might like
关于PHP5 Session生命周期介绍
2010/03/02 PHP
php实现阳历阴历互转的方法
2015/10/28 PHP
PHP Laravel 上传图片、文件等类封装
2017/08/16 PHP
JavaScript中的Document文档对象
2008/01/16 Javascript
js获取客户端外网ip的简单实例
2013/11/21 Javascript
innerHTML,outerHTML,innerText,outerText的用法及区别解析
2013/12/16 Javascript
JavaScript中的值类型详细介绍
2014/12/29 Javascript
js如何实现淡入淡出效果
2020/11/18 Javascript
JS中事件冒泡和事件捕获介绍
2016/12/13 Javascript
从零学习node.js之express入门(六)
2017/02/25 Javascript
layer弹窗插件操作方法详解
2017/05/19 Javascript
AngularJS中下拉框的高级用法示例
2017/10/11 Javascript
vue中如何动态绑定图片,vue中通过data返回图片路径的方法
2018/02/07 Javascript
脚手架vue-cli工程webpack的基本用法详解
2018/09/29 Javascript
JavaScript 复制对象与Object.assign方法无法实现深复制
2018/11/02 Javascript
layui的表单提交以及验证和修改弹框的实例
2019/09/09 Javascript
vue实现计算器功能
2020/02/22 Javascript
vue中实现点击空白区域关闭弹窗的两种方法
2020/12/30 Vue.js
[09:13]2014DOTA2国际邀请赛 中国区预选赛coser表演
2014/05/23 DOTA
python开发的小球完全弹性碰撞游戏代码
2013/10/15 Python
在Python中使用__slots__方法的详细教程
2015/04/28 Python
Python 查看文件的编码格式方法
2017/12/21 Python
Python Flask前后端Ajax交互的方法示例
2018/07/31 Python
python Gunicorn服务器使用方法详解
2019/07/22 Python
Python中six模块基础用法
2019/12/08 Python
在matplotlib中改变figure的布局和大小实例
2020/04/23 Python
iframe与window.onload如何使用详解
2020/05/07 HTML / CSS
狗狗玩具、零食和咀嚼物的月度送货服务:Super Chewer
2018/08/22 全球购物
Feelunique中文官网:欧洲最大化妆品零售电商
2020/07/10 全球购物
mysql有关权限的表都有哪几个
2015/04/22 面试题
客户代表自我评价范例
2013/09/24 职场文书
机电专业毕业生推荐信
2013/11/10 职场文书
应届生的求职推荐信范文
2013/11/30 职场文书
4s店机修工岗位职责
2013/12/20 职场文书
五年级科学教学反思
2014/02/05 职场文书
奖学金主要事迹范文
2015/11/04 职场文书