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

作者:David Beazley 时间:2021-10-06 05:45:32 

问题

你想解析某个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解析稍微简单一点。

来源:https://python3-cookbook.readthedocs.io/zh_CN/latest/c06/p07_parse_xml_documents_with_namespaces.html

标签:Python,命名空间,解析XML
0
投稿

猜你喜欢

  • Python微服务开发之使用FastAPI构建高效API

    2022-04-20 21:51:13
  • 年底了,你的mysql密码安全吗

    2024-01-12 23:50:00
  • 对Django中static(静态)文件详解以及{% static %}标签的使用方法

    2021-03-27 20:28:21
  • Django中modelform组件实例用法总结

    2023-09-28 14:35:49
  • SQL文本字段的数字排序问题

    2008-11-18 16:47:00
  • Python中reduce函数详解

    2022-09-03 12:26:33
  • SQL语句之WHERE子句的使用方法

    2007-08-11 12:25:00
  • SQL SERVER 建立索引

    2010-07-02 21:01:00
  • ASP提速技巧五则

    2008-03-20 13:20:00
  • ASP生成XML文件

    2009-06-29 16:28:00
  • 浅谈Python3中print函数的换行

    2023-12-15 18:24:31
  • 关于Python中进度条的六个实用技巧分享

    2023-07-03 09:58:39
  • ACCESS中Field对象的标题属性

    2008-11-20 17:44:00
  • python计算机视觉opencv矩形轮廓顶点位置确定

    2022-06-07 16:30:44
  • JavaScript中一个奇葩的IE浏览器判断方法

    2024-04-17 10:24:44
  • python使用ctypes库调用DLL动态链接库

    2023-12-08 14:14:05
  • Pycharm 字体大小调整设置的方法实现

    2023-10-23 19:35:11
  • 浅谈Python之Django(三)

    2021-07-07 00:38:25
  • 浅谈常用Java数据库连接池(小结)

    2024-01-18 06:50:25
  • Pycharm学习教程(7)虚拟机VM的配置教程

    2022-10-12 16:49:33
  • asp之家 网络编程 m.aspxhome.com