开发者社区> 问答> 正文

利用命名空间解析XML文档

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

展开
收起
哦哦喔 2020-04-17 13:20:11 799 0
1 条回答
写回答
取消 提交回答
  • 考虑下面这个使用了命名空间的文档:
    
    <?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'
    >>>
    
    2020-04-17 13:20:36
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
神龙云服务器产品及技术深度解析 立即下载
弹性创造价值:基于ECS的最佳性价比实践解析 立即下载
又快又稳:阿里云下一代虚拟交换机解析 立即下载

相关镜像