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解决Fedora解压zip时中文乱码的方法
Sep 18 Python
Python机器学习之决策树算法
Dec 22 Python
Python从零开始创建区块链
Mar 06 Python
selenium在执行phantomjs的API并获取执行结果的方法
Dec 17 Python
深入浅析python3中的unicode和bytes问题
Jul 03 Python
Python3 requests文件下载 期间显示文件信息和下载进度代码实例
Aug 16 Python
Django通过dwebsocket实现websocket的例子
Nov 15 Python
pytorch: Parameter 的数据结构实例
Dec 31 Python
pycharm不能运行.py文件的解决方法
Feb 12 Python
如何使用python传入不确定个数参数
Feb 18 Python
django orm模块中的 is_delete用法
May 20 Python
教你使用Python pypinyin库实现汉字转拼音
May 27 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+Ajax实现唯一校验实现代码[简单应用]
2011/11/29 PHP
PHP语言中global和$GLOBALS[]的分析 之二
2012/02/02 PHP
CodeIgniter启用缓存和清除缓存的方法
2014/06/12 PHP
非常好用的Zend Framework分页类
2014/06/25 PHP
php数据访问之查询关键字
2016/05/09 PHP
php项目中类的自动加载实例讲解
2019/09/12 PHP
PHP封装请求类实例分析【基于Yii框架】
2019/10/17 PHP
PHP Beanstalkd消息队列的安装与使用方法实例详解
2020/02/21 PHP
extjs两个tbar问题探讨
2013/08/08 Javascript
在javascript中如何得到中英文混合字符串的长度
2014/01/17 Javascript
JavaScript数据结构与算法之栈与队列
2016/01/29 Javascript
详解Javascript继承的实现
2016/03/25 Javascript
jquery自定义表单验证插件
2016/10/12 Javascript
JS中解决谷歌浏览器记住密码输入框颜色改变功能
2017/02/13 Javascript
JS对象与JSON互转换、New Function()、 forEach()、DOM事件流等js开发基础小结
2017/08/10 Javascript
详解如何使用koa实现socket.io官网的例子
2018/11/04 Javascript
vue.draggable实现表格拖拽排序效果
2018/12/01 Javascript
JS如何寻找数组中心索引过程解析
2020/06/01 Javascript
Vue实现多页签组件
2021/01/14 Vue.js
Element-ui 自带的两种远程搜索(模糊查询)用法讲解
2021/01/29 Javascript
Python内存管理方式和垃圾回收算法解析
2017/11/11 Python
Ubuntu下使用python读取doc和docx文档的内容方法
2018/05/08 Python
解决springboot yml配置 logging.level 报错问题
2020/02/21 Python
python 瀑布线指标编写实例
2020/06/03 Python
python合并多个excel文件的示例
2020/09/23 Python
美国知名珠宝首饰品牌:Gemvara
2017/10/06 全球购物
英国文胸专家:AmpleBosom.com
2018/02/06 全球购物
主键(Primary Key)约束和唯一性(UNIQUE)约束的区别
2013/05/29 面试题
咖啡馆创业计划书
2014/01/26 职场文书
图书馆志愿者活动总结
2014/06/27 职场文书
党员个人对照检查材料思想汇报
2014/09/16 职场文书
基层党员群众路线教育实践活动个人对照检查材料思想汇报
2014/10/05 职场文书
2015年元宵节活动总结
2015/02/06 职场文书
《葡萄沟》教学反思
2016/02/23 职场文书
超级实用!五步法则,教你写好年终工作总结
2019/12/05 职场文书
win10更新失败无限重启解决方法
2022/04/19 数码科技