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使用chardet判断字符编码
May 09 Python
深入解析Python中的__builtins__内建对象
Jun 21 Python
用tensorflow搭建CNN的方法
Mar 05 Python
Tensorflow实现卷积神经网络用于人脸关键点识别
Mar 05 Python
详解利用django中间件django.middleware.csrf.CsrfViewMiddleware防止csrf攻击
Oct 09 Python
python tkinter界面居中显示的方法
Oct 11 Python
Python3+PyInstall+Sciter解决报错缺少dll、html等文件问题
Jul 15 Python
Python的bit_length函数来二进制的位数方法
Aug 27 Python
python实现滑雪者小游戏
Feb 22 Python
Python编程快速上手——正则表达式查找功能案例分析
Feb 28 Python
Python定时从Mysql提取数据存入Redis的实现
May 03 Python
matplotlib.pyplot.matshow 矩阵可视化实例
Jun 16 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
PHP SEO优化之URL优化方法
2011/04/21 PHP
Win2003+apache+PHP+SqlServer2008 配置生产环境
2014/07/29 PHP
PHP实现CSV文件的导入和导出类
2015/03/24 PHP
php实现面包屑导航例子分享
2015/12/19 PHP
基于prototype扩展的JavaScript常用函数库
2010/11/30 Javascript
js实现简单随机抽奖的方法
2015/01/27 Javascript
JS组件Bootstrap Table布局详解
2016/05/27 Javascript
微信jssdk用法汇总
2016/07/16 Javascript
纯javaScript、jQuery实现个性化图片轮播【推荐】
2017/01/08 Javascript
JS简单获取日期相差天数的方法
2017/04/24 Javascript
vue.js中引入vuex储存接口数据及调用的详细流程
2017/12/14 Javascript
使用async-validator编写Form组件的方法
2018/01/10 Javascript
vue-cli中vue本地实现跨域调试接口
2019/01/16 Javascript
用webpack4开发小程序的实现方法
2019/06/04 Javascript
jQuery实现判断滚动条滚动到document底部的方法分析
2019/08/27 jQuery
layui lay-verify form表单自定义验证规则详解
2019/09/18 Javascript
微信小程序复选框实现多选一功能过程解析
2020/02/14 Javascript
python3.6的venv模块使用详解
2018/08/01 Python
python配置文件写入过程详解
2019/10/19 Python
如何用Anaconda搭建虚拟环境并创建Django项目
2020/08/02 Python
python 生成器需注意的小问题
2020/09/29 Python
Vision Directa智利眼镜网:框架眼镜、隐形眼镜和名牌太阳眼镜
2016/11/23 全球购物
美国卡车、吉普车和SUV零件网站:4 Wheel Parts
2016/11/24 全球购物
德国著名廉价网上药店:Shop-Apotheke
2017/07/23 全球购物
Needle & Thread官网:英国仙女品牌
2018/01/13 全球购物
教师师德承诺书
2014/03/26 职场文书
教师个人自我评价范文
2014/04/13 职场文书
工厂搬迁方案
2014/05/11 职场文书
2014年最新版离婚协议书范本
2014/11/25 职场文书
项目经理岗位职责
2015/01/31 职场文书
学生保证书格式
2015/02/27 职场文书
研讨会通知
2015/04/27 职场文书
初中生活随笔
2015/08/15 职场文书
带你学习MySQL执行计划
2021/05/31 MySQL
梳理总结Python开发中需要摒弃的18个坏习惯
2022/01/22 Python
Java中的Kotlin 内部类原理
2022/06/16 Java/Android