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项目发布为exe可执行程序过程分享
Oct 23 Python
python实现的简单FTP上传下载文件实例
Jun 30 Python
pytorch构建网络模型的4种方法
Apr 13 Python
Python中文件的读取和写入操作
Apr 27 Python
Python根据文件名批量转移图片的方法
Oct 21 Python
Python中的正则表达式与JSON数据交换格式
Jul 03 Python
图解python全局变量与局部变量相关知识
Nov 02 Python
关于TensorFlow新旧版本函数接口变化详解
Feb 10 Python
python读取excel进行遍历/xlrd模块操作
Jul 12 Python
python实现最短路径的实例方法
Jul 19 Python
python 第三方库paramiko的常用方式
Feb 20 Python
Python 居然可以在 Excel 中画画你知道吗
Feb 15 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 pki加密技术(openssl)详解
2013/07/01 PHP
php计算数组不为空元素个数的方法
2014/01/27 PHP
Codeigniter中mkdir创建目录遇到权限问题和解决方法
2014/07/25 PHP
php使用正则表达式进行字符串搜索的方法
2015/03/23 PHP
PHP的AES加密算法完整实例
2016/07/20 PHP
php-fpm开启状态统计的方法详解
2017/06/23 PHP
php设计模式之单例模式用法经典示例分析
2019/09/20 PHP
firefox和IE系列的相关区别整理 以备后用
2009/12/28 Javascript
Document对象内容集合(比较全)
2010/09/06 Javascript
JS打开图片另存为对话框实现代码
2012/12/26 Javascript
Javascript中的异步编程规范Promises/A详细介绍
2014/06/06 Javascript
简单的jquery左侧导航栏和页面选中效果
2014/08/21 Javascript
Spring Boot+AngularJS+BootStrap实现进度条示例代码
2017/03/02 Javascript
js实现适配不同的屏幕大小
2017/04/10 Javascript
浅谈vuex 闲置状态重置方案
2018/01/04 Javascript
微信小程序前端自定义分享的实现方法
2019/06/13 Javascript
vue中的 $slot 获取插槽的节点实例
2019/11/12 Javascript
Vue $attrs &amp; inheritAttr实现button禁用效果案例
2020/12/07 Vue.js
JS实现公告上线滚动效果
2021/01/10 Javascript
python通过urllib2爬网页上种子下载示例
2014/02/24 Python
跟老齐学Python之Python安装
2014/09/12 Python
利用python和百度地图API实现数据地图标注的方法
2019/05/13 Python
探秘TensorFlow 和 NumPy 的 Broadcasting 机制
2020/03/13 Python
jupyter 导入csv文件方式
2020/04/21 Python
Html5新增标签与样式及让元素水平垂直居中
2019/07/11 HTML / CSS
HTML5 History API 实现无刷新跳转
2016/01/11 HTML / CSS
Lookfantastic瑞典:英国知名美妆购物网站
2018/04/06 全球购物
Chupi官网:在爱尔兰手工制作的订婚、结婚戒指和精美珠宝
2020/09/28 全球购物
出纳员岗位职责风险
2014/03/06 职场文书
十佳中学生事迹材料
2014/06/02 职场文书
会计专业应届生自荐信
2014/06/28 职场文书
忠诚奉献演讲稿
2014/09/12 职场文书
基层党员群众路线教育实践活动个人对照检查材料思想汇报
2014/10/05 职场文书
亚布力滑雪场导游词
2015/02/09 职场文书
虎兄虎弟观后感
2015/06/12 职场文书
工作简报范文
2015/07/21 职场文书